使用Tab键关注按钮,然后按enter键

时间:2015-06-18 03:30:27

标签: java swing netbeans jbutton actionlistener

我有一个带有提交按钮和取消按钮的简单jFrame。目前,一切都很完美。用户在鼠标单击时执行操作。现在我想首先按下'tab'来聚焦按钮,然后每当有人按下回车键时它就会触发。它应该适用于两个键。我在这里错过了什么?我正在使用netbean IDE。下面是使用鼠标点击完美运行的代码示例。

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
         String ws = null;
         if(unitno.getText().length() == 14)
        {
            String substr=unitno.getText().substring(unitno.getText().length()-4);
            if (substr.equals("0678"))
            {
                model.setSelectedItem("Tesla");
            }
            else if(substr.equals("0675"))
            {
                 model.setSelectedItem("Weber Base");
            }
            else if(substr.equals("0676"))
            {
                 model.setSelectedItem("Weber Mid");
            }
               else if(substr.equals("0677")|| substr.equals("067j")|| substr.equals("067J"))
            {
                 model.setSelectedItem("Weber PDL");
            }
        }
        try{
             Double wd = Double.parseDouble(w.getText());
             if(wd<251.43 || wd>253.03){
                  w.setForeground(Color.BLUE);
                  w.setBackground(Color.YELLOW);
                  wt.setForeground(Color.red);
             }
             else{
                   ws = w.getText();
                  w.setForeground(Color.BLACK);
                  w.setBackground(Color.WHITE);
             }

             if(ws ==null || unitno.getText().equals("")){
                int dialogButton = JOptionPane.YES_NO_OPTION;
                int dialogResult = JOptionPane.showConfirmDialog(this, "Empty field or out of spec is detected. Press YES to save and NO to edit.", "Error", dialogButton);
                if(dialogResult ==0){
                    ws = w.getText();

                    w.setForeground(Color.BLACK);
                    w.setBackground(Color.WHITE);  

                    BufferedWriter output = null;
                    FileInputStream fs = null;
                    FileWriter fout = null;

                    try {
                        // TODO add your handling code here:
                        File desktop = new File(System.getProperty("user.home"), "Desktop");
                       // Double total = Double.parseDouble(ba) + Double.parseDouble(fr) ;
                        File dir = new File (desktop + "/WattCPC");
                        if(!dir.exists()){
                            dir.mkdirs();
                        }
                        File myFile = new File(desktop + "/WattCPC/topextimechwidth.txt");
                        if(!myFile.exists()) {
                            myFile.createNewFile();
                        } 
                        fs = new FileInputStream(desktop + "/WattCPC/topextimechwidth.txt");
                        BufferedReader br = new BufferedReader(new InputStreamReader(fs));
                        output = new BufferedWriter(new FileWriter(myFile,true));
                        PrintWriter fileout = new PrintWriter(output,true);
                        if (br.readLine() == null) {
                               fileout.println("Model" + "," + "Date" + "," + "Line" + "," + "Shift" + "," + "Unit Number" + "," + "Width");
                         }
                        DateFormat dateFormat = new SimpleDateFormat("MMM/dd/yyyy hh:mm");
                        Date date = new Date();
                        for(int i = 1; i<100; ++i){
                            String linez = br.readLine();
                            if(linez==null){
                               fileout.println(model.getSelectedItem() + "," + dateFormat.format(date) + "," + line.getSelectedItem() + "," + shift.getSelectedItem() + "," + unitno.getText() + "," + ws  );
                               break;
                            }
                        }        
                    } catch (IOException ex) {
                        Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        try {
                            output.close();
                        } catch (IOException ex) {
                            Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    JOptionPane msg = new JOptionPane("Saved successfully", JOptionPane.INFORMATION_MESSAGE);
                    final JDialog dlg = msg.createDialog("Message");
                    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                    new Thread(new Runnable() {    

3 个答案:

答案 0 :(得分:3)

一些外观(看着你的金属)使用 Space 键作为&#34;操作键&#34;。一个简单的解决方案是使用不同的外观,个人而言,我更喜欢系统的外观和感觉,因为它应该以用户用于当前系统的方式工作。

&#34;行动&#34; key将在触发时调用所有已注册的ActionListener

如果出于某种原因,您无法更改外观,则可以使用添加键绑定到JButton

JButton press = new JButton("Press me");
InputMap im = press.getInputMap(WHEN_FOCUSED);

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released");

JButton已经有一个名为pressedreleased的注册密钥绑定,通常配置为默认&#34;操作&#34;关键,这样做只是重复使用,所以当你按下默认的&#34;动作&#34; key OR 输入键,他们会做同样的事情,你不需要做任何额外的编码。

请参阅How to Use Key Bindings

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());

            JButton press = new JButton("Press me");
            InputMap im = press.getInputMap(WHEN_FOCUSED);

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released");

            press.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(TestPane.this, "You rang master?");
                }
            });

            add(press);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

这很麻烦,因为您需要为每个JButton执行此操作,创建自定义JButton并使用它来代替或提供某种工厂方法来为您执行配置,这些都不是特别令人愉快的解决方案。

您拥有的另一个解决方案是创建自己的外观代理并替换默认委托。这不是很漂亮,并且有自己需要考虑的问题(比如你从哪个代表延伸,如果外观改变会发生什么?)

答案 1 :(得分:0)

使用键绑定将 Enter 键注册到JButton,如下所示:

KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER);
String action = "Enter"
Action enterAction = new AbstractAction(ActionEvent evt){
    @Override
    public void actionPerformed(ActionEvent e) {
        jButton1ActionPerformed(evt);
    }
};
jButton1.getInputMap(WHEN_FOCUSED).put(enterKeyStroke, action);
jButton1.getActionMap().put(action, enterAction);

我希望这能解决你的问题。

答案 2 :(得分:0)

https://stackoverflow.com/a/16923982/1614775。 它建议

UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);