Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to attach an <code>ItemListener</code> to your combo box. On change, you need to determine the selected item (<code>JComboBox.getSelectedItem</code> or <code>JComboBox.getSelectedIndex</code>) and update the image as required...</p> <p>You can also use you existing <code>ActionListener</code> instead</p> <p><img src="https://i.stack.imgur.com/fzFJN.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/hXj3j.png" alt="enter image description here"></p> <pre><code>public class SwitchPicture { public static final String[] IMAGES = new String[]{ "path/to/your/first/image", "path/to/your/second/image" }; public static void main(String[] args) { new SwitchPicture(); } public SwitchPicture() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new SwitcherPane()); frame.pack(); frame.setVisible(true); } }); } protected class SwitcherPane extends JPanel { private BufferedImage[] images; private JLabel lblBackground; private JComboBox comboBox; public SwitcherPane() { try { images = new BufferedImage[2]; for (int index = 0; index &lt; 2; index++) { images[index] = ImageIO.read(new File(IMAGES[index])); } } catch (IOException ex) { ex.printStackTrace();; } setLayout(new BorderLayout()); lblBackground = new JLabel(); lblBackground.setIcon(new ImageIcon(images[0])); add(lblBackground); comboBox = new JComboBox(); comboBox.getSelectedItem() // I did this because the images where so large // you couldn't see the combo box :P comboBox.setFont(comboBox.getFont().deriveFont(48f)); DefaultComboBoxModel&lt;String&gt; model = new DefaultComboBoxModel&lt;&gt;(); model.addElement("Happy"); model.addElement("Happier"); comboBox.setModel(model); comboBox.setSelectedIndex(0); lblBackground.setLayout(new GridBagLayout()); lblBackground.add(comboBox); comboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { lblBackground.setIcon(new ImageIcon(images[comboBox.getSelectedIndex()])); } }); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload