简体   繁体   English

使用Tab键将焦点放在按钮上,然后按Enter

[英]Focus on the button using tab key and press enter

I have a simple jFrame with a submit button and a cancel button. 我有一个带有提交按钮和取消按钮的简单jFrame。 Currently, everything works perfectly. 目前,一切正常。 User perform action on mouse click. 用户单击鼠标即可执行操作。 Now I want to press 'tab' first to focus the button then it should fire whenever someone presses the enter key. 现在,我想先按“ Tab”键使按钮聚焦,然后每当有人按Enter键时它就会触发。 It should work for both keys. 它应该对两个键都起作用。 What am I missing here? 我在这里想念什么? I am using netbean IDE. 我正在使用netbean IDE。 Below is a sample of the code that works perfectly using mouse click. 下面是使用鼠标单击即可完美工作的代码示例。

 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() {    

Some look and feels (looking at you Metal) use the Space key as the "action key". 有些外观(看着您的Metal)将空格键用作“操作键”。 A simple solution would be to use a different look at feel, personally, I prefer the system look and feel for this reason, it should work in ways that the user is use to for the current system. 一个简单的解决方案是使用不同的外观,我个人更喜欢系统外观,因此,它应该以用户习惯于当前系统的方式工作。

The "action" key will call all the registered ActionListener s when triggered 触发时,“操作”键将调用所有已注册的ActionListener

If, for some reason, you are unable to change the look and feel, you could use add a key binding to the JButton 如果由于某种原因您无法更改外观,则可以使用向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");

A JButton already has a registered key binding called pressed and released which is generally configured for the default "action" key, what this does is simply reuses that, so that when you press the default "action" key OR Enter key, they will do the same thing, you don't need to do any extra coding. 一个JButton已经有一个被称为“ pressedreleased的注册键绑定,通常将其配置为默认的“动作”键,这样做只是简单地重用了它,因此当您按下默认的“动作”键或Enter键时,它们将同样,您无需进行任何额外的编码。

See 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);
        }

    }

}

This is cumbersome, as you will either need to do this for every JButton you have, create a custom JButton and use that instead or provide some kind of factory method to perform the configuration for you, none of which are particular pleasant solutions. 这很麻烦,因为您将需要为拥有的每个JButton执行此操作,创建一个自定义JButton并使用它,或者提供某种工厂方法来为您执行配置,这些都不是特别令人愉快的解决方案。

The other solution you have is to create your own look and feel delegate and replace the default delegate. 您拥有的另一个解决方案是创建自己的外观委托并替换默认委托。 This is not pretty and has it's own issues which need to be considered (like which delegate do you extend from, what happens if the look and feel is changed?) 这不是很漂亮,并且需要考虑它自己的问题(例如,您是从哪个代表扩展而来的,如果外观改变了,会发生什么?)

Use key binding to register the pressing of Enter key to the JButton as shown below: 使用键绑定将按下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);

I hope this will solve your problem. 我希望这能解决您的问题。

See https://stackoverflow.com/a/16923982/1614775 . 参见https://stackoverflow.com/a/16923982/1614775 It suggests 这表明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM