1

我有一个 JPanel,它使用 KeyListener 作为内容窗格作为窗口;但是,在 JPanel 顶部的网格布局中有按钮和文本字段。

如何在编辑文本或单击按钮后保留焦点的 JPanel 的焦点优先级以便我可以读取键输入?

4

2 回答 2

0

您只需要FocusListenerfocusLost事件上添加一个,然后再次请求焦点。像这样的东西:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JPanelFocus {
  public static void main(String... argv) throws Exception {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        JFrame f = new JFrame("FocusTest");
        JButton b = new JButton("Button");
        final JPanel p = new JPanel();
        p.add(b);
        // Here is the KeyListener installed on our JPanel
        p.addKeyListener(new KeyAdapter() {
          public void keyTyped(KeyEvent ev) {
            System.out.println(ev.getKeyChar());
          }
        });
        // This is the bit that does the magic - make sure
        // that our JPanel is always focussed
        p.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent ev) {
            p.requestFocus();
          }
        });
        f.getContentPane().add(p);
        f.pack();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        // Make sure JPanel starts with the focus
        p.requestFocus();
      }
    });
  }
}

如果您有需要保持焦点的字段(您提到了可编辑的文本字段),这将不起作用。关键事件什么时候应该转到文本字段,什么时候应该转到 JPanel?

于 2013-06-07T10:03:46.950 回答
0

作为替代方案,您也可以只使子组件不可聚焦。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyPanel extends JPanel implements KeyListener {
    public MyPanel() {
        this.setFocusable(true);
        this.addKeyListener(this);

        // for each component
        JComboBox<String> comboBox = new JComboBox<String>();
        comboBox.addItem("Item1");
        this.add(comboBox);
        // this is what keeps each child from intercepting KeyEvents
        comboBox.setFocusable(false);
    }

    public void keyPressed(KeyEvent e) { ... }
    public void keyTyped(KeyEvent e) { ... }
    public void keyReleased(KeyEvent e) { ... }

    public static void main(String[] args) {
        // create a frame
        JFrame frame = new JFrame();
        frame.setSize(640, 480);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // add MyPanel to frame
        MyPanel panel = new MyPanel();
        frame.add(panel);
        frame.setVisible(true);
    }
}
于 2014-08-25T02:40:39.600 回答