我希望JButton
中的唯一JFrame
成为默认按钮,并在其容器中的任意位置回复ENTER
。
所以我打电话给JRootPane#setDefaultButton(theButton)
但没有任何反应:
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);
}
}
当我点击btn
时,文字会按预期更改,但按ENTER
则不会执行任何操作(我必须TAB
按下按钮,然后我才能按ENTER
并获得所需的结果。)