给予JPanel优先关注

时间:2013-05-18 21:04:44

标签: java swing focus jpanel keylistener

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

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

2 个答案:

答案 0 :(得分:0)

您只需在FocusListener事件上添加focusLost,然后再次请求重点关注。像这样:

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?

答案 1 :(得分: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);
    }
}