【发布时间】:2018-12-07 13:49:34
【问题描述】:
在我的程序中,由侦听器使用 KeyBindings 操作的 JPanel 组件(在阅读有关聚焦问题后已经从 KeyListeners 更改了该组件)被添加到 JFrame。这个应用程序的任务是使用箭头键简单地移动绘制的图形。 在我在绘图板之前添加另一个组件(带有三个按钮的 JPanel)之前,这非常有效。 我测试了 Keybindings 和 KeyListener ,这两种方法都有同样的问题。 如果我在绘图板键绑定再次开始工作后添加组件。
这是我添加组件的 UI 类。
EDIT: removed uncleaned code
我想更多地了解 Java,因此非常感谢任何答案。
编辑:我清理了我的代码并创建了问题的“最小”示例。 感谢 Andrew 的提醒。
按向上箭头后,程序应在控制台中打印“movingup”。
问题出现在这里:
container.add(buttons); //after adding this Key Bindings stops working
container.add(board);
问题是:为什么添加组件的顺序会使 Key Bindings 停止工作?如果我在 board 键绑定工作后添加 buttons。
有问题的类(用于创建框架和添加组件)
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.WindowConstants;
public class UserInterface implements Runnable {
private static final String MOVE_UP = "moveUP";
private JFrame frame;
public UserInterface() {
}
@Override
public void run() {
frame = new JFrame("Board");
frame.setPreferredSize(new Dimension(500, 400));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout());
createComponents(frame.getContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void createComponents(Container container) {
DrawingBoard board = new DrawingBoard();
container.add(new JButton()); //after adding this figure stops moving - arrow keys doesn't work
container.add(board);
MovingUpwards up = new MovingUpwards(board);
board.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
board.getInputMap().put(KeyStroke.getKeyStroke("UP"), MOVE_UP);
board.getActionMap().put(MOVE_UP, up);
}
public JFrame getFrame() {
return frame;
}
}
其余用于测试目的的类:
import javax.swing.SwingUtilities;
public class Main {
public static void main (String[] args) {
UserInterface ui = new UserInterface();
SwingUtilities.invokeLater(ui);
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawingBoard extends JPanel {
public DrawingBoard() {
super.setBackground(Color.WHITE);
}
@Override
protected void paintComponent (Graphics graphics) {
super.paintComponent(graphics);
}
}
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
public class MovingUpwards extends AbstractAction {
private Component component;
public MovingUpwards(Component component) {
this.component = component;
}
@Override
public void actionPerformed(ActionEvent a) {
System.out.println("movingup");
}
}
【问题讨论】:
-
1) "..so 任何答案都非常感谢。" 任何问题都是如此。关于这个问题,您有个问题吗?如果是这样,请将其添加为edit。 2) 为了尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
标签: java swing jframe awt key-bindings