我正在开发Java Swing应用程序。
当我按下enter键时,左右键切换焦点,按钮焦点激活。 我的问题是如何使按钮焦点响应输入密钥。
private void displayGUI(){
JFrame w = new buildFrame();
w.setDef
aultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
w.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
Object[] options = {"YES","NO","CANCEL"};
JOptionPane optionPane = new JOptionPane("File haven't save yet." +
" \n Are you want to save the file?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_CANCEL_OPTION,
null,
options);
JDialog dialog = optionPane.createDialog("Confirm Dialog");
Set<AWTKeyStroke> forwardTraversalKeys =
new HashSet<AWTKeyStroke>(dialog.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
forwardTraversalKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.VK_UNDEFINED));
Set<AWTKeyStroke> backwardTraversalKeys =
new HashSet<AWTKeyStroke>(dialog.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
backwardTraversalKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_LEFT, KeyEvent.VK_UNDEFINED));
dialog.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardTraversalKeys);
dialog.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardTraversalKeys);
dialog.setVisible(true);
Object n = optionPane.getValue();
if(n.toString().equals("YES")){
if(helper.saveFile("text.txt", gatherAllContent(), Swing4.this)){
System.exit(0);
}
label.setText("There is something wrong on quit");
}else if(n.toString().equals("NO")){
System.exit(0);
}else if(n.toString().equals("CANCEL")){
dialog.setVisible(false);
dialog.dispose();
}
}
});
w.setSize(600,600);
w.setLocation(700,100);
w.setVisible(true);
}
方法的代码dialogEnterKeyAction