简体   繁体   中英

Display image when JcomboBox item is selected

What I want to do is to display an image when a specified item is selected from the comboBox, knowing that the items of the comboBox change and the number is not fix. This code shows how I add the items which depends on my "for"

for (int j = 1; j <= 6; j++) {
    if (condition) {
    System.out.println(result); 
        combo.addItem("component N°" + j);
    }
}

What I need is to display a certain image when a an item is selected! I really don't know how to do it. I've tried actionperformed with actionlistener, but I didn't know how to relate the item choosing with my images.

I use this method to display an image into JPanel

public static void display(String path, JPanel panel) {
    BufferedImage image = null;
    try {
        image = ImageIO.read(new File(path));
    } catch (IOException e2) {

        e2.printStackTrace();
    }
    Image dimg = image.getScaledInstance(panel.getWidth(), panel.getHeight(),
            Image.SCALE_SMOOTH);
    panel.add(new JLabel(new ImageIcon(dimg)));

}

For example if I select (component N° 2) from the JcomboBox then the image that I need to display is image2.png (j=2)

Simply add ActionListener and retrieve the number from the selected item. You can use JLabel to show the images. Simply call setIcon() to change the icon.

Sample code:

//final JLabel label = new JLabel();

final ComboBox<String> jComboBox = new JComboBox<String>();
jComboBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String value=(String)jComboBox.getSelectedItem();
        int digit =Integer.valueOf(value.replaceAll("component N°","").trim());
        String imageName="image"+digit+".png";

        // show the image  
        // label.setIcon(...);          
    }
});

Please have a look at my another post. It might help you to form the correct image path.


I just had one image displayed but when I change the combobox item nothing happens

EDIT (remove already added image before adding new one)

 public static void display(String path, JPanel panel){
    ...
    panel.removeAll();                          // Remove already added image
    panel.add(new JLabel(new ImageIcon(dimg))); // Add new image
    panel.revalidate();
    panel.repaint();
 }

To work with JCombobox you need to use the ItemStateChanged method. In that method you can get the selected index. Then from the index you can get the data in the index. Now you have the chosen data and can do what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM