簡體   English   中英

除非先單擊JButton,否則keyPressed不起作用

[英]keyPressed doesn't work unless JButton clicked first

我創建了一個使用JButton遞增數字的小應用程序。 這些按鈕不是可單擊的,而是由鍵盤激活的(即textField中的數字隨鍵盤的按下而增加,而不是通過鼠標單擊按鈕來增加)。 我的問題是,在首次啟動該應用程序時,鍵盤沒有執行任何操作,直到我先單擊其中一個按鈕為止-即使單擊該按鈕不會執行任何操作。 我試圖使按鈕之一requestFocusInWindow()認為,如果它已經集中在上面,那么鍵就可以工作,但是無論將其放在主方法還是控制器類中,這似乎都行不通。 我試圖找出是否需要執行KeyboardFocusManageraddFocusListener() (但是我不希望按鈕獲得/失去焦點時總會發生某些事情)。 我已經嘗試了很多東西,試圖將其添加到帶有frame的主方法或控制器類中。 以下是我當前的代碼:

主班

import javax.swing.JFrame;

public class Count {

    public static void main(String[] args) {
        CountController frame = new CountController();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(560, 150); 
        frame.setVisible(true); 
        //I've tried to add the button and requestFocusInWindow here
        //as well as tried a frame.addWindowFocusListener
    }
} // end class

控制器類

imports ...
public class CountController extends JFrame implements KeyListener {
    private JLabel ...
    private JTextField ...
    private JButton ....
    int ...
    // no-argument constructor
    public CountController() {
        super("Title");
        setLayout(null); // position GUI components explicitly

        //set up JLabels in following manner
        label = new JLabel("some label");
        label.setBounds(47, 5, 45, 25);
        label.setHorizontalAlignment(JLabel.CENTER);
        add(label);

        //set up JTextFields in following manner
        textField = new JTextField("0");
        textField.setBounds(47, 30, 45, 25);
        textField.setHorizontalAlignment(JTextField.CENTER);
        textField.setBackground(Color.WHITE);
        textField.setEditable(false);
        add(textField);

        //set up JButtons in the following manner
        button = new JButton("some text");
        button.setBounds(15, 70, 110, 25);
        button.setBackground(Color.WHITE);
        add(button);
        button.addKeyListener(this);
        //I've tried adding requestFocusInWindow() here as well
    } // end constructor

    //begin KeyListener stuff
    @Override
    public void keyPressed(KeyEvent event){
        int keyCode = event.getKeyCode();
        switch(keyCode){
            case #: //# is ASCII #
                do some things;
                call a method();
                break;
        }
    }
    @Override
    public void keyReleased(KeyEvent event){
        button.setBackground(Color.WHITE);
    }
    @Override
    public void keyTyped(KeyEvent event){
        // nothing but this is needed for implementing KeyListener
    }

    //List of methods that are called from switch
        ...

    //I've tried to add a public void initialize(){}

}//end CountController class

我將不勝感激,希望它能起作用,因此我不必先單擊按鈕即可操作鍵。 謝謝!

為了使偵聽器觸發事件​​,必須先將其注冊為組件並使其具有焦點。 請改用按鍵綁定API

下面使用JComponent.WHEN_IN_FOCUSED_WINDOW定義將在其下生成鍵事件的上下文。 在這種配置下,什么焦點都沒有關系,只要窗口當前處於焦點狀態,事件仍然會生成

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

public class Count {

  public static void main(String[] args) {
    CountController frame = new CountController();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(560, 150);
    frame.setVisible(true);
    //I've tried to add the button and requestFocusInWindow here
    //as well as tried a frame.addWindowFocusListener
  }

  public static class CountController extends JFrame {

    // no-argument constructor
    public CountController() {
      super("Title");
      setLayout(new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridwidth = GridBagConstraints.REMAINDER;

      //set up JLabels in following manner
      JLabel label = new JLabel("some label");
      label.setHorizontalAlignment(JLabel.CENTER);
      add(label, gbc);

      //set up JTextFields in following manner
      JTextField textField = new JTextField("0", 20);
      textField.setHorizontalAlignment(JTextField.CENTER);
      textField.setBackground(Color.WHITE);
      textField.setEditable(false);
      add(textField, gbc);

      //set up JButtons in the following manner
      JButton button = new JButton("some text");
      add(button, gbc);

      InputMap im = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
      ActionMap am = button.getActionMap();

      im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, KeyEvent.SHIFT_DOWN_MASK), "Pressed.#");
      am.put("Pressed.#", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
          textField.setText(textField.getText() + "#");
        }
      });

    } // end constructor

  }//end CountController class
} // end class

盡管我將綁定綁定注冊到父容器而不是按鈕上,但這僅是我自己。

而且,不使用null布局的原因...這就是您原始代碼在我的PC上的樣子

不使用空布局的原因

盡管我不清楚您的代碼應該完成什么操作,但是您的問題是您將addKeyListener(this)到了button但是按鈕沒有焦點,並且按下鍵時它什么也沒做。 嘗試將KeyListener()添加到其他GUI組件(例如, textfield ,因為它是第一個組件,並且專注於start(從您提供的代碼開始),然后查看它是否起作用。

暫無
暫無

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

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