Search code examples
javaswingjpaneljlabelmouselistener

Displaying JLabel based on combobox option


How do I display a JLabel based on a combobox option. When I run the code all the JLabels are displayed straight away.

combo1.addActionListener(this);
panel.add(combo1);
panel.add(img1);
panel.add(img2);
panel.add(img3);

frame.add(panel);

    img1.setText("<html> Image : <a href=\"\">Image1/</a></html>");   
    img2.setText("<html> Image : <a href=\"\">Image2/</a></html>");
    img3.setText("<html> Image : <a href=\"\">Image3/</a></html>");

    img1.setCursor(new Cursor(Cursor.HAND_CURSOR));
    img2.setCursor(new Cursor(Cursor.HAND_CURSOR));
    img3.setCursor(new Cursor(Cursor.HAND_CURSOR));

I'm using mouseListener to check which label is passed into the goWebsite() function, and then according to that it'll add a hyperlink to the label.

private void goWebsite(final JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(website == img1){
                try {
                    Desktop.getDesktop().browse(new URI("http://2.bp.blogspot.com/_2dxp9ORKKAM/TBZpViy7O1I/AAAAAAAABGY/zitq3ZLA8K4/s1600/red.png"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
                if(website == img2){
                    try {
                        Desktop.getDesktop().browse(new URI("http://www.pratikbagaria.com/wp-content/uploads/2011/04/BlueGreenPink.jpg"));
                    } catch (URISyntaxException | IOException ex) {
                        //It looks like there's a problem
                    }
                }
                if(website == img3){
                    try {
                        Desktop.getDesktop().browse(new URI("http://i.imgur.com/9OPnZNk.png"));
                    } catch (URISyntaxException | IOException ex) {
                        //It looks like there's a problem
                    }
                }
                if(website == img4){
                    try {
                        Desktop.getDesktop().browse(new URI("http://www.solidbackgrounds.com/images/three/2048x2048/2048x2048-fluorescent-orange-fluorescent-pink-fluorescent-yellow-three-color-background.jpg"));
                    } catch (URISyntaxException | IOException ex) {
                        //It looks like there's a problem
                    }
                }

The actionPerformed checks which option from the combobox the user has selected and then passes the right img JLabel into the goWebsite() function.

@Override
    public void actionPerformed(ActionEvent e)
    {
        String color1 = (String)combo1.getSelectedItem();
        // Possibly check if either color is 'null' here
        if (color1.equals("red") )
        {

            goWebsite(img1);
        }
        if (color1.equals("blue") )
        {

            goWebsite(img2);
        }
        if (color1.equals("green") )
        {

            goWebsite(img3);
        }
}

Solution

  • Try adding a ItemListener to the JComboBox, when itemStateChanged is called, check that the ItemEvent#getStateChanged equals ItemEvent.SELECTED.

    Check what is selected in the combo box (or use ItemEvent#ItemSelected) and either update a single JLabel with the information you want OR make the current label associated with the selected item visible by using JLabel#setVisible(true), but also make sure you hide the others

    For example...

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class ComboBoxUpdate {
    
        public static void main(String[] args) {
            new ComboBoxUpdate();
        }
    
        public ComboBoxUpdate() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private JComboBox comboBox;
            private JLabel option1;
            private JLabel option2;
            private JLabel option3;
    
            public TestPane() {
                comboBox = new JComboBox(new String[]{"Choice 1", "Choice 2", "Choice 3"});
                option1 = new JLabel("Bananas");
                option2 = new JLabel("Appels");
                option3 = new JLabel("Grapes");
                option1.setVisible(false);
                option2.setVisible(false);
                option3.setVisible(false);
    
                setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
    
                add(comboBox, gbc);
                add(option1, gbc);
                add(option2, gbc);
                add(option3, gbc);
    
                comboBox.addItemListener(new ItemListener() {
                    @Override
                    public void itemStateChanged(ItemEvent e) {
                        switch (e.getStateChange()) {
                            case ItemEvent.SELECTED:
                                Object value = comboBox.getSelectedItem();
                                option1.setVisible(false);
                                option2.setVisible(false);
                                option3.setVisible(false);
                                if ("Choice 1".equals(value)) {
                                    option1.setVisible(true);
                                } else if ("Choice 2".equals(value)) {
                                    option2.setVisible(true);
                                } else if ("Choice 3".equals(value)) {
                                    option3.setVisible(true);
                                }
                                break;
                        }
                    }
                });
    
                comboBox.setSelectedItem(null);
            }
        }
    }