1

我正在开发 Java Swing 应用程序。

焦点通过左右键切换,当我按下回车键时按钮焦点处于活动状态。我的问题是如何使按钮焦点响应输入键。

    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 的代码

4

1 回答 1

4

有关一种解决方案,请参见Enter Key and Button

于 2013-04-08T17:31:04.413 回答