我正在尝试使用ImageIcon和addMouseListener从JFrame上的图像创建一个buttom,它将通过单击将当前图像替换为另一个图像。
static JPanel jp = new JPanel();
final JLabel jl = new JLabel();
final JFrame jf = new JFrame();
ImageIcon image = new ImageIcon("image1.jpg");
jl.setIcon(image);
jp.add(jl);
jf.add(jp);
jf.validate();
JLabel button = new JLabel(image);
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
jl.setIcon( null );
ImageIcon image = new ImageIcon("image2.jpg");
jl.setIcon(image);
}
});
GUI与image1.jpg一起显示,但按钮完全不起作用,我甚至无法测试从image1到image2的替换是否有效。即使我尝试单击窗口上显示的image1.jpg,GUI也不会执行任何操作。
编辑:调整后的JLabel变量现在是最终的。其他类似的问题,这个方法应该有效,但我无法弄清楚代码有什么问题。
答案 0 :(得分:0)
不确定ActionListener是否也适用于JLabel。
不,您无法将ActionListener添加到JLabel。更简单的方法是使JButton看起来像JLabel,然后您可以将ActionListener添加到按钮:
JButton button = new JButton(...);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.addActionListener(...);
但按钮根本不起作用
当收到相同鼠标点的mousePressed和mouseReleased时,会生成鼠标单击。因此,如果稍微移动鼠标,则不会生成事件。而是监听mousePressed()事件。