如何在单击按钮的帮助下更改图片。
我创建了一个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();
}
}
答案 0 :(得分:0)
<script href="<c:url value="/resources/js/app.js"/>"></script>
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel();
panel.add(pic1);
ImageIcon icon1 = new ImageIcon("pic1.gif");
ImageIcon icon2 = new ImageIcon("pic2.gif");
ImageIcon icon3 = new ImageIcon("pic3.gif");
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
if(x == 0){
pic1.setIcon(icon1);
}else if(x == 1){
pic1.setIcon(icon2);
}else if(x == 2){
pic1.setIcon(icon3);
}
Main.this.pack();
x++;
if(x > 2) x = 0;
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
,而是使用3 JLabel
。 ImageIcon
JFrame
这种情况,改变图像)