编译时,我有一个空白窗口。没有元素添加到主框架。我错过了什么?
public class Gui extends JFrame {
private JComboBox<String> box;
private JLabel picture;
private static String[] filename = {"pic1", "pic2.png" };
private Icon[] pics = { new ImageIcon(getClass().getResource(filename[0])),
new ImageIcon(getClass().getResource(filename[1])) };
Gui() {
super("window");
setLayout(new FlowLayout());
setVisible(true);
setSize(600, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
box = new JComboBox<String>(filename);
box.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
});
picture = new JLabel(pics[0]);
add(picture);
add(box);
}
}
答案 0 :(得分:0)
可能出现的问题: 1.确保用于图片的相对或绝对路径正确。 2.在创建此类对象的位置,需要调用t.setVisible(true)。 (即看看我的主要方法)
public class Gui extends JFrame {
private JComboBox<String> box;
private JLabel picture;
private static String[] filename = {"C:\\Users\\..\\pic1.jpg","C\\Users\\..\\pic2.jpg" };
private Icon[] pics = { new ImageIcon(filename[0]),
new ImageIcon(filename[1] ) };
Gui() {
super("window");
setLayout(new FlowLayout());
setVisible(true);
setSize(600, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
box = new JComboBox<String>(filename);
box.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
});
picture = new JLabel(pics[0]);
add(picture);
add(box);
}
public static void main(String[] args){
Gui t = new Gui();
t.setVisible(true);
}