【问题标题】:Image button created from JLabel is not working从 JLabel 创建的图像按钮不起作用
【发布时间】:2013-08-16 22:19:11
【问题描述】:

我正在尝试使用 ImageIcon 和 addMouseListener 从 JFrame 上的图像创建一个按钮,通过单击它将当前图像替换为另一个图像。

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 变量调整为现在是最终的。其他类似的问题暗示这种方法应该可以工作,但我无法弄清楚代码有什么问题。

【问题讨论】:

  • 您应该为按钮使用ActionListener
  • 我只是想让图像可以点击来命令一个动作。也不确定 ActionListener 是否可以与 JLabel 一起使用。
  • 您的“按钮”变量是什么类类型?请说明它是如何声明和初始化的。您的标题表明它是 JLabel,如果是这样,则变量名称具有高度误导性,因为它表明它实际上是 JButton 或类似的东西。考虑澄清您的问题。
  • 请不要将 JLabel 对象命名为“按钮”。同样,这具有误导性。
  • 看起来您已经向名为“button”的 JLabel 添加了一个 MouseListener,我没有看到它添加到面板中。您是否点击了名为“jl”的 JLabel,认为它是“按钮”?

标签: java


【解决方案1】:

不太确定 ActionListener 是否也适用于 JLabel。

不,您不能将 ActionListener 添加到 JLabel。更简单的方法是让 JButton 看起来像 JLabel,然后您可以将 ActionListener 添加到按钮:

JButton button = new JButton(...);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.addActionListener(...);

但按钮根本不起作用

当针对同一鼠标点接收到 mousePressed 和 mouseReleased 时,将生成鼠标单击。因此,如果您稍微移动鼠标,则不会生成事件。而是监听 mousePressed() 事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2018-09-27
    • 2014-02-16
    • 2012-09-17
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    相关资源
    最近更新 更多