【发布时间】:2017-08-05 16:34:25
【问题描述】:
如何在点击按钮的帮助下切换图片。
我创建了一个 x 变量,因为这样我可以创建不同的 if 语句,但这对我不起作用,可能是因为我做错了什么……这是我目前的代码:
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private JLabel pic2;
private JLabel pic3;
private JLabel picture;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel(new ImageIcon("pic1.png"));
pic2 = new JLabel(new ImageIcon("pic.png"));
pic3 = new JLabel(new ImageIcon("pic3.png"));
panel.add(pic1);
panel.add(pic2);
panel.add(pic3);
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
【问题讨论】:
-
“但这对我不起作用”你能澄清一下“不起作用”吗?您究竟希望您的代码做什么,是什么让您这么想,以及会发生什么?
-
当我按下按钮时它没有交换图片。我看到的唯一图像是 first(pic1) changePic.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(e.getSource() == changePic){ if(x == 0){ 面板。 add(pic1); }else if(x == 1){ panel.add(pic2); }else if(x == 2){ panel.add(pic3); } x++; if(x > 2) x = 0; } } });
-
使用edit 选项来更新您的问题,包括问题描述和代码(因为它在评论部分不可读)。
-
无论如何这可能会让你感兴趣How to change icon of a JLabel?
-
1) 有关使用
JButton启动和停止在循环中显示图像数组(在JLabel中)的SwingTimer的示例,请参见this answer。它将为您提供所需答案的许多部分。例如。将x更改为counter,然后将其用作数组的索引。 2) 总是edit 带有新代码的问题。在评论中几乎无法阅读。
标签: java swing jbutton jlabel imageicon