簡體   English   中英

使用Tab鍵將焦點放在按鈕上,然后按Enter

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

我有一個帶有提交按鈕和取消按鈕的簡單jFrame。 目前,一切正常。 用戶單擊鼠標即可執行操作。 現在,我想先按“ Tab”鍵使按鈕聚焦,然后每當有人按Enter鍵時它就會觸發。 它應該對兩個鍵都起作用。 我在這里想念什么? 我正在使用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() {    

有些外觀(看着您的Metal)將空格鍵用作“操作鍵”。 一個簡單的解決方案是使用不同的外觀,我個人更喜歡系統外觀,因此,它應該以用戶習慣於當前系統的方式工作。

觸發時,“操作”鍵將調用所有已注冊的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的注冊鍵綁定,通常將其配置為默認的“動作”鍵,這樣做只是簡單地重用了它,因此當您按下默認的“動作”鍵或Enter鍵時,它們將同樣,您無需進行任何額外的編碼。

請參閱如何使用鍵綁定

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並使用它,或者提供某種工廠方法來為您執行配置,這些都不是特別令人愉快的解決方案。

您擁有的另一個解決方案是創建自己的外觀委托並替換默認委托。 這不是很漂亮,並且需要考慮它自己的問題(例如,您是從哪個代表擴展而來的,如果外觀改變了,會發生什么?)

使用鍵綁定將按下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);

我希望這能解決您的問題。

參見https://stackoverflow.com/a/16923982/1614775 這表明

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM