【问题标题】:How to create a rollover button in swing如何在摇摆中创建一个翻转按钮
【发布时间】:2013-10-14 18:25:07
【问题描述】:

所以我有两个按钮,

JButton playB = new JButton(new ImageIcon("res/playA.png"));
playB.setBorder(BorderFactory.createEmptyBorder());
playB.setContentAreaFilled(false);
JButton playA = new JButton(new ImageIcon("res/playA.png"));
playA.setBorder(BorderFactory.createEmptyBorder());
playA.setContentAreaFilled(false);

我将如何创建它,以便当我将鼠标移到按钮 A 上时它会切换到按钮 B?我能想到的只是使用鼠标侦听器,但我想知道是否有更好的方法。

【问题讨论】:

  • 你切换的目的是什么? JButtons 是非常模态的,你可以根据上下文对它做任何事情。

标签: java swing jbutton rollover


【解决方案1】:

我将如何创建它,以便当我将鼠标移到按钮 A 上时 切换到按钮 B?我能想到的就是用鼠标 听众,但我想知道是否有更好的方法。

注意:setRolloverIcon 方法不能用于此。

  • 这个想法,用两个JButtons切换不是...,也不是使用MouseListener,因为所有的鼠标和按键事件都在JButtons APi中实现并且正确

  • JButton.setRolloverIcon 与来自ButtonModel 的事件一起使用,输出应该是两个Swing Actions,而不是在运行时添加两个JButtons,并带有ActionListeners

例如

JButton.getModel().addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        ButtonModel model = (ButtonModel) e.getSource();
        if (model.isRollover()) {
            //doSomething
        } else if (model.isPressed()) {
           //doSomething
        }  // etc
    }
});

编辑

又回来了

我将如何创建它,以便当我将鼠标移到按钮 A 上时 切换到按钮 B?我能想到的就是用鼠标 听众,但我想知道是否有更好的方法。

  • 结论首先JButton (button A) 不是,用户端永远无法从MouseKeyEvents 访问,因为这两个事件都会(立即)将其转换为roll_over

  • 那么只有一种方法,以编程方式从KeyBindings 调用JButton.doClick(),但仍然存在问题,何时、如何以及为什么……将简单的事情复杂化

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2012-11-15
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多