JRootPane#setDefaultButton(theButton) does nothing

岁酱吖の 提交于 2019-12-12 03:53:17

问题


I want my only JButton in the JFrame to be the default button and respond to ENTER press anywhere in its container.

So I called the JRootPane#setDefaultButton(theButton) but nothing happens:

package tests;

import org.junit.Test;
import javax.swing.*;
import java.awt.*;

public class HierarchyTest {
    @Test
    public void test(){
        JDialog win = new JDialog(null, "test", Dialog.ModalityType.APPLICATION_MODAL);
        win.setBounds(600,300,400,200);
        CommonPanel panel = new CommonPanel();
        win.add(panel);
        panel.init();
        win.setVisible(true);
    }
}

CommonPanel:

package tests;

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

class CommonPanel extends JPanel {

    private final JButton btn;
    private final String format = "<html><style> code { font-size: inherit; } </style>" +
            "<body style='font-size:18px'><h1>%s</h1>%s</body></html>";

    CommonPanel() {
        setLayout(new BorderLayout());

        final JTextPane pane = new JTextPane();
        pane.setContentType("text/html");
        pane.setEditable(false);
        pane.setText(String.format(format, "TITLE", "BODY"));
        add(pane, BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        add(bottomPanel, BorderLayout.SOUTH);

        btn = new JButton("Change text");
        btn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                pane.setText(String.format(format, "Yeaaaaaay!!!", "The eagle has landed!!!"));
            }
        });
        bottomPanel.add(btn);
    }

    void init() {
        JRootPane rootPane = SwingUtilities.getRootPane(btn);
        rootPane.setDefaultButton(btn);
    }
}

When I click btn the text changes as expected, but pressing ENTER does nothing (I must TAB my way to the button and only then I can press ENTER and get the desired result).

来源:https://stackoverflow.com/questions/41315304/jrootpanesetdefaultbuttonthebutton-does-nothing

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