Java isRollover() method does not produce an event in my swing application

守給你的承諾、 提交于 2019-12-05 10:38:18
trashgod

Code as tested on Leopard with Java version 1.6.0_26 shown below. The trailing </html> tag fixed a highlighting glitch on rollover.

Addendum: Using the updated example below, adding setRolloverEnabled(true) allows the model to work as expected. Interestingly, the Mac UI delegate, com.apple.laf.AquaButtonUI, does nothing when isRollover() is true. If it's important to your application, you can take the desired action when the following predicate is true:

System.getProperty("os.name").startsWith("Mac OS X")

For reference, this example demonstrates setRolloverIcon().

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class ChangeDemo {

    private JButton jbtn;
    private JLabel jlab;

    public ChangeDemo() {
        JFrame jfrm = new JFrame("Button Change Events");
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrm.setLayout(new GridLayout(0, 1));
        jlab = new JLabel("", JLabel.CENTER);
        jbtn = new JButton("Press for Change Event Test");
        jbtn.setRolloverEnabled(true);

        jbtn.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent ce) {
                ButtonModel mod = jbtn.getModel();
                String what = "";

                if (mod.isEnabled()) {
                    what += "Enabled<br>";
                }
                if (mod.isRollover()) {
                    what += "Rollover<br>";
                }
                if (mod.isArmed()) {
                    what += "Armed<br>";
                }
                if (mod.isPressed()) {
                    what += "Pressed<br>";
                }

                //Notice that this label's text is HTML
                jlab.setText("<html>Current stats:<br>" + what + "</html>");
            }
        });

        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(50, 10, 0, 10));
        panel.add(jbtn);
        jfrm.add(panel);
        jfrm.add(jlab);

        jfrm.pack();
        jfrm.setLocationRelativeTo(null);
        jfrm.setVisible(true);
    }

    public static void main(String[] args) {
        //Create the frame on the event dispatching thread
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ChangeDemo changeDemo = new ChangeDemo();
            }
        });
    }
}

Okay okay. I know this has been answered really well already, and the OP's question was on a Mac, but this answer needs sharin'.

If you are on Windows 7, rollover effects won't work if you have the theme set to "Classic". Set it to "Basic" and rollovers will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!