当我为我的JFrame中的每个JPanel添加了绑定时,我会假设当我按下W
键时至少会触发其中一个。我的KeyStroke
不正确吗?
SSCCE:
public class TestTemp extends JFrame {
public TestTemp() {
setSize(1000, 800);
JPanel parentPanel = new JPanel(new MigLayout("", "grow, fill",
"grow, fill"));
parentPanel.setBackground(Color.GREEN);
setContentPane(parentPanel);
parentPanel.setSize(1000, 800);
JPanel videoPanel = new JPanel();
videoPanel.setBackground(Color.CYAN);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new MigLayout("fillx", "[fill]", "[nogrid]"));
contentPanel.setBackground(Color.YELLOW);
parentPanel.getInputMap().put(KeyStroke.getKeyStroke("W"), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W pressed, parent panel");
}
});
contentPanel.getInputMap().put(KeyStroke.getKeyStroke("W"), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W pressed, content panel");
}
});
videoPanel.getInputMap().put(KeyStroke.getKeyStroke("W"), new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("W pressed, video panel");
}
});
parentPanel.add(videoPanel, "wmin 200");
parentPanel.add(contentPanel);
}
public static void main(String[] args) {
JFrame frame = new TestTemp();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
编辑:
我试图使用以下内容给出parentPanel
焦点:
parentPanel.setFocusable(true);
parentPanel.requestFocus();
但似乎没有任何效果。
编辑2: 为了确保它不是一个不正确的击键,我使用了文档在他们的示例中给出的击键:
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)
但同样,点击Enter
没有效果。
答案 0 :(得分:0)
试试这个:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;
public class T extends JFrame {
public T() {
setSize(1000, 800);
JPanel parentPanel = new JPanel(new MigLayout("", "grow, fill",
"grow, fill"));
parentPanel.setBackground(Color.GREEN);
getContentPane().add(parentPanel);
parentPanel.setSize(1000, 800);
JPanel videoPanel = new JPanel();
videoPanel.setBackground(Color.CYAN);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new MigLayout("fillx", "[fill]", "[nogrid]"));
contentPanel.setBackground(Color.YELLOW);
parentPanel.getActionMap().put("enter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Enter pressed, parent panel");
}
});
InputMap inputMap = parentPanel.getInputMap();
inputMap.put( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "enter");
parentPanel.add(videoPanel, "wmin 200");
parentPanel.add(contentPanel);
}
public static void main(String[] args) {
JFrame frame = new T();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我认为MigLayout不是问题所在。
getActionMap
代替getInputMap
等待操作事件。InputMap
分开以听取击键。 enter
键盘事件现在写入标准输出。
有关详细信息,请参阅以下链接:
一般来说,当您遇到困难问题时,请尝试使最简单的案例工作。一旦你有最简单的案例工作(例如,一个面板接受键盘输入),然后建立复杂性。例如,您甚至可以删除MigLayout以查看它是否影响键盘输入。