Java swing Combobox里如何根据不同的选项,实时显示出不同的图片?
2个回答
展开全部
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends JFrame{
private JLabel label = null;
private JComboBox box = null;
private String img1 = "d://1.JPG";
private String img2 = "d://2.JPG";
public Test(){
setSize(500,500);
setLocation(100,50);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(getPanel());
setVisible(true);
}
private Container getPanel() {
JPanel panel = new JPanel();
panel.setLayout(null);
label = new JLabel();
//label 设置一张图片,
label.setIcon(new ImageIcon(img1));
box = new JComboBox(new String[]{"图片1","图片2"});
box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取当前选择项的下标
int i = box.getSelectedIndex();
if(i == 0){
label.setIcon(new ImageIcon(img1));
}else{
label.setIcon(new ImageIcon(img2));
}
}
});
label.setBounds(60, 10, 200, 200);
box.setBounds(60, 300, 100,40);
panel.add(label);
panel.add(box);
return panel;
}
public static void main(String[] args) {
new Test();
}
}
图片的地址自己改一下就能看到效果
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends JFrame{
private JLabel label = null;
private JComboBox box = null;
private String img1 = "d://1.JPG";
private String img2 = "d://2.JPG";
public Test(){
setSize(500,500);
setLocation(100,50);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(getPanel());
setVisible(true);
}
private Container getPanel() {
JPanel panel = new JPanel();
panel.setLayout(null);
label = new JLabel();
//label 设置一张图片,
label.setIcon(new ImageIcon(img1));
box = new JComboBox(new String[]{"图片1","图片2"});
box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取当前选择项的下标
int i = box.getSelectedIndex();
if(i == 0){
label.setIcon(new ImageIcon(img1));
}else{
label.setIcon(new ImageIcon(img2));
}
}
});
label.setBounds(60, 10, 200, 200);
box.setBounds(60, 300, 100,40);
panel.add(label);
panel.add(box);
return panel;
}
public static void main(String[] args) {
new Test();
}
}
图片的地址自己改一下就能看到效果
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询