我想实现的是在一个界面上有一个按钮,按下这个按钮后会改变这个界面的背景图片。但是我把那个改变图片的代码加入监听事件后,按下按钮并没有反应,图片并未改变。但是我如果未加入监听事件,直接把改变背景的代码放在后边,运行后背景就变了。我想知道这个该如何解决,谢谢各位大佬
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class test extends JFrame implements ActionListener
{
private JButton but2;
public JLabel imgLabel;
public test()
{
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int)dim.getWidth();
int height = (int)dim.getHeight();
this.setSize(dim);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
ImageIcon img = new ImageIcon("C:\\Users\\Cy\\Pictures\\1.png");
JLabel imgLabel = new JLabel(img);
this.getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE));
imgLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
Container contain = this.getContentPane();
((JPanel) contain).setOpaque(false);
Color c=new Color(2,2,255);
but2=new JButton();
this.add(but2);
but2.setBackground(c);
but2.setOpaque(false);
but2.setBorderPainted(false);
but2.setBounds(width-height/10, height*2/7-height/10, 100,100);
ImageIcon icon2 =new ImageIcon("C:\\\\Users\\\\Cy\\\\Pictures\\\\cal.png");
but2.setIcon(icon2);
/*
ImageIcon img2 = new ImageIcon("C:\\Users\\Cy\\Pictures\\star.png");
imgLabel.setIcon(img2);
imgLabel.setBounds(-60, -50, img.getIconWidth(), img.getIconHeight());
but2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == but2)
{
JLabel imgLabel=new JLabel();
ImageIcon img2 = new ImageIcon("C:\\Users\\Cy\\Pictures\\star.png");
imgLabel.setIcon(img2);
imgLabel.setBounds(0, 0, img2.getIconWidth(), img2.getIconHeight());
}
}
}
https://jingyan.baidu.com/article/358570f60bf78cce4724fc0c.html?st=2&os=0&bd_page_type=1&net_type=2