问题
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