簡體   English   中英

用鍵按下時如何使這些按鈕起作用?

[英]How to make these Buttons function when pressed with a key?

  1. 這是代碼。
  2. 如果我不首先單擊該按鈕,則該按鈕不起作用。 如果您能幫助我,那就太好了。

創建框架時使用了eclipse

這只是一個示例代碼,但我只想知道它的功能

有關其他細節,請在此處詢問。

    import java.awt.EventQueue;

    import javax.swing.JFrame;
    import javax.swing.JButton;

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JTextField;


    public class ExampleApp {

    private JFrame frmHi;
    private JTextField textField;
    private JButton btnAnother;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ExampleApp window = new ExampleApp();
                    window.frmHi.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ExampleApp() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmHi = new JFrame();
        frmHi.setTitle("Hi");
        frmHi.setBounds(100, 100, 450, 300);
        frmHi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmHi.getContentPane().setLayout(null);

        JButton btnEnter = new JButton("Enter");
        btnEnter.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    textField.setText("You pressed enter");
                }
            }
        });
        btnEnter.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText("Hi there from button");
            }
        });
        btnEnter.setBounds(119, 63, 89, 23);
        frmHi.getContentPane().add(btnEnter);

        textField = new JTextField();
        textField.setEnabled(false);
        textField.setEditable(false);
        textField.setBounds(108, 30, 173, 20);
        frmHi.getContentPane().add(textField);
        textField.setColumns(10);

        btnAnother = new JButton("Backspace");
        btnAnother.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent arg0) {
                if (arg0.getKeyCode() == KeyEvent.VK_BACK_SPACE){
                    textField.setText("you pressed backspace");
                }
            }
        });
        btnAnother.setBounds(119, 119, 89, 23);
        frmHi.getContentPane().add(btnAnother);
    }

}

您的KeyListener已添加到JButton中,因此僅在按鈕具有焦點(單擊后)時才可以使用。

最好為必須處理的鍵定義KeyBindings

暫無
暫無

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

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