Java 选择JcomboBox项时显示图像

Java 选择JcomboBox项时显示图像,java,swing,Java,Swing,我想做的是,当从组合框中选择指定的项目时,显示一个图像,知道组合框中的项目发生变化,并且数字不固定。此代码显示如何添加依赖于“for”的项 要使用JCombobox,您需要使用ItemStateChanged方法。在该方法中,您可以获得所选索引。然后从索引中可以得到索引中的数据。现在您已经选择了数据,可以做您想做的事情了 例如,如果我从JcomboBox中选择(组件编号2),那么我需要显示的图像是image2.png(j=2) 只需添加ActionListener,然后从所选项目中检索号码。您可

我想做的是,当从组合框中选择指定的项目时,显示一个图像,知道组合框中的项目发生变化,并且数字不固定。此代码显示如何添加依赖于“for”的项


要使用JCombobox,您需要使用
ItemStateChanged
方法。在该方法中,您可以获得所选索引。然后从索引中可以得到索引中的数据。现在您已经选择了数据,可以做您想做的事情了

例如,如果我从JcomboBox中选择(组件编号2),那么我需要显示的图像是image2.png(j=2)

只需添加
ActionListener
,然后从所选项目中检索号码。您可以使用
JLabel
显示图像。只需调用
setIcon()
即可更改图标

示例代码:

//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(...);          
    }
});

您希望如何将图像与组合框的值关联起来?图像的名称是否源自所选项目?例如,如果我从JcomboBox中选择(组件编号2),那么我需要显示的图像是image2.png(j=2)。组合框中的内容与图像有何关联?如果您不知道这是如何工作的,那么我们的建议将无济于事。一种可能性是设计一个
对象
,其中包含一个
字符串
和对要加载的图像的引用。
字符串
已被用作组合框和图像中显示的内容,以便您可以加载/显示it@MadProgrammer我试图调查这个问题,但OP正在分块共享代码。我已经浪费了一个多小时来解决它,但我不知道OP在做什么。现在请你继续。我要睡觉了。欲了解更多信息,请阅读我文章的评论。1)欲更快获得更好的帮助,请发布一个(最少完整且可验证的示例)。2) 不要将多个标签添加到同一空间,而只添加一个标签。保留对它的引用。在执行操作时,将新图标设置为单个标签。
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)));

}
//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(...);          
    }
});
 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();
 }