简体   繁体   English

如何将鼠标侦听器添加到JOptionPane按钮?

[英]How to add mouse listener to JOptionPane button?

I want to change appearance of Button on JOptionPane.ShowMessageDialog. 我想更改JOptionPane.ShowMessageDialog上Button的外观。 I have managed to change Button caption with 我设法用更改了按钮标题

UIManager.put("OptionPane.okButtonText", "Text I want");

Now, my next goal is to make Button work same as buttons in rest of my app. 现在,我的下一个目标是使Button与我的其余应用程序中的按钮相同。 That is, when hovering mouse over it, it changes background and font color. 也就是说,将鼠标悬停在其上时,它将更改背景和字体颜色。 On rest of my buttons I added mouse listener like this one: 在其余的按钮上,我添加了像这样的鼠标监听器:

    //setting change color on hover
        private final MouseListener mouseAction = new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                JButton rollOver = (JButton)e.getSource();
                if (rollOver.isEnabled()) {
                    rollOver.setBackground(new Color(163, 184, 204));
                    rollOver.setForeground(Color.WHITE);
                    rollOver.setFont(b);
                }
            };

            @Override
            public void mouseExited(MouseEvent e) {
                JButton rollOver = (JButton)e.getSource();
                if (rollOver.isEnabled()) {
                    rollOver.setBackground(new Color(230, 230, 230));
                    rollOver.setForeground(Color.BLACK);
                    rollOver.setFont(f);
                }
            };
        };

Previously in code I have Font varibles set: 以前在代码中我设置了Font varibles:

    Font f = new Font("System", Font.PLAIN, 12);
    Font b = new Font("System", Font.BOLD, 12);

I could make new dialogs from scratch and implent this behaviour but that would be overkill. 我可以从头开始进行新的对话,并阻止这种行为,但这太过分了。

Is there some way to access Button on JOptionPane and add mouse listener to it? 有什么方法可以访问JOptionPane上的Button并为其添加鼠标侦听器?

If you want to see the same effect inside all OptionPanels, I think the override BasicOptionPaneUI is a good solution 如果您想在所有OptionPanel中看到相同的效果,我认为重写BasicOptionPaneUI是一个很好的解决方案

This is a minimal example 这是一个最小的例子

public class MyOptionPaneUI extends BasicOptionPaneUI {

    @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
    public static ComponentUI createUI(JComponent c) {
        return new MyOptionPaneUI();
    }

    private static final MyMouseListener m = new MyMouseListener();

    @Override
    public void update(Graphics g, JComponent c) {
        super.update(g, c);
    }

    @Override
    protected void installListeners() {
       JButton button = (JButton) getButtons()[0];
        button.addMouseListener(m);

        super.installListeners();
    }

    @Override
    protected void uninstallListeners() {
        JButton button = (JButton) getButtons()[0];
        button.removeMouseListener(m);

        super.uninstallListeners();
    }

    public static class MyMouseListener extends MouseAdapter{
        @Override
        public void mouseEntered(MouseEvent e) {
            JButton rollOver = (JButton)e.getSource();
            if (rollOver.isEnabled()) {
                rollOver.setBackground(new Color(163, 184, 204));
                rollOver.setForeground(Color.WHITE);
            }
        };

        @Override
        public void mouseExited(MouseEvent e) {
            JButton rollOver = (JButton)e.getSource();
            if (rollOver.isEnabled()) {
                rollOver.setBackground(new Color(230, 230, 230));
                rollOver.setForeground(Color.BLACK);
            }
        };
    }
}

inside your frame your main class you can add this code for load the class inside the UIDefoult 在您的主类中,您可以添加此代码以将类加载到UIDefoult中

static{
   UIManager.put("OptionPaneUI", MyOptionPaneUI.getClass().getCanonicalName());
}

Because getButtons()[0] , because I see this code inside the BasicOptionPaneUI 因为getButtons()[0] ,因为我在BasicOptionPaneUI里面看到了这段代码

else if (type == JOptionPane.OK_CANCEL_OPTION) {
                    defaultOptions = new ButtonFactory[2];
                    defaultOptions[0] = new ButtonFactory(
                        UIManager.getString("OptionPane.okButtonText",l),
                        getMnemonic("OptionPane.okButtonMnemonic", l),
                        (Icon)DefaultLookup.get(optionPane, this,
                                          "OptionPane.okIcon"), minimumWidth);
                    defaultOptions[1] = new ButtonFactory(
                        UIManager.getString("OptionPane.cancelButtonText",l),
                        getMnemonic("OptionPane.cancelButtonMnemonic", l),
                        (Icon)DefaultLookup.get(optionPane, this,
                                          "OptionPane.cancelIcon"), minimumWidth);
                } else {
                    defaultOptions = new ButtonFactory[1];
                    defaultOptions[0] = new ButtonFactory(
                        UIManager.getString("OptionPane.okButtonText",l),
                        getMnemonic("OptionPane.okButtonMnemonic", l),
                        (Icon)DefaultLookup.get(optionPane, this,


                "OptionPane.okIcon"), minimumWidth);
            }

inside the method protected Object[] getButtons() 在方法protected Object[] getButtons()


If you want the effect mouse hover on the button I'm working on this library and have the solution for the mouse over. 如果您想将效果鼠标悬停在按钮上,我正在使用此库,并提供了鼠标悬停的解决方案。

If you have a possibility to personalize the DefaoultButton inside the library with this constant 如果您可以使用此常量个性化库中的DefaoultButton

UIManager.put("Button[Default].background", new Color(163, 184, 204));
UIManager.put("Button[Default].foreground", Color.WHITE);
UIManager.put("Button[Default].mouseHoverColor", new Color(230, 230, 230));

ps: this is only information if you need to add the mouse hover inside the you project ps:仅当您需要在项目中添加鼠标悬停时才提供此信息

UIManager.put("OptionPane.okButtonText", "Text I want");

The above will change the text for all "Ok" buttons on all JOptionPanes that you create. 上面的代码将更改您创建的所有JOptionPanes上所有“确定”按钮的文本。

If you want to change the text on an individual button on a specific JOptionPane then read the section from the Swing tutorial on Customizing Button Text . 如果要更改特定JOptionPane上单个按钮上的文本,请阅读Swing教程中有关“ 自定义按钮文本”的部分

Is there some way to access Button on JOptionPane and add mouse listener to it? 有什么方法可以访问JOptionPane上的Button并为其添加鼠标侦听器?

When you use the static showXXX(...) methods a modal JDialog is created so you don't have access to the dialog or its components until the dialog is closed which is too late. 当您使用静态showXXX(...)方法时,会创建一个模态JDialog,因此您无法访问对话框或其组件,直到对话框关闭为时已晚。

So instead you need to manually create the JOptionPane and add it to a JDialog . 因此,您需要手动创建JOptionPane并将其添加到JDialog The basics of doing this can be found by reading the JOptionPane API and looking at the section titled "Direct Use" . 可以通过阅读JOptionPane API并查看标题为"Direct Use"的部分来找到执行此操作的基础。

Once you have created the JOptionPane (and before you make the dialog visible) you can then search the option pane for the buttons and add a MouseListener to each button. 创建JOptionPane (在使对话框可见之前),您可以在选项窗格中搜索按钮,并将MouseListener添加到每个按钮。 To help you with this you can use the Swing Utils class. 为了帮助您解决此问题,您可以使用Swing Utils类。 It will do a recursive search of the option pane and return the buttons to you in a List . 它将对选项窗格进行递归搜索,并在List中将按钮返回给您。 You can then iterate through the List and add the MouseListener . 然后,您可以遍历List并添加MouseListener

The basic code using this helper class would be: 使用此帮助程序类的基本代码为:

JOptionPane optionPane = new JOptionPane(
    "Are you sure you want to exit the application",
    JOptionPane.QUESTION_MESSAGE,
    JOptionPane.YES_NO_CANCEL_OPTION);

List<JButton> buttons = SwingUtils.getDescendantsOfType(JButton.class, optionPane, true);

for (JButton button: buttons)
{
    System.out.println( button.getText() );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM