我正在尝试制作一个程序,您可以在其中使用箭头键在 java swing 窗口中移动一个圆圈。键绑定工作正常,但显示圆圈总是有问题。这是代码:
public class ShapesMove extends JFrame{
public static int x = 40;
public static int y = 40;
public static void main(String[] args){
final JFrame frame = new JFrame("Movement of 2d Shapes");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = (JPanel) frame.getContentPane();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Action actionRight = new AbstractAction(){
public void actionPerformed(ActionEvent actionRightEvent){
x++;
}
};
Action actionLeft = new AbstractAction(){
public void actionPerformed(ActionEvent actionLeftEvent){
x--;
}
};
Action actionUp = new AbstractAction(){
public void actionPerformed(ActionEvent actionUpEvent){
y++;
}
};
Action actionDown = new AbstractAction(){
public void actionPerformed(ActionEvent actionDownEvent){
y--;
}
};
KeyStroke right = KeyStroke.getKeyStroke("RIGHT");
KeyStroke left = KeyStroke.getKeyStroke("LEFT");
KeyStroke up = KeyStroke.getKeyStroke("UP");
KeyStroke down = KeyStroke.getKeyStroke("DOWN");
InputMap inputMap = content.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(right, "RIGHT");
inputMap.put(left, "LEFT");
inputMap.put(up, "UP");
inputMap.put(down, "DOWN");
content.getActionMap().put("RIGHT", actionRight);
content.getActionMap().put("LEFT", actionLeft);
content.getActionMap().put("UP", actionUp);
content.getActionMap().put("DOWN", actionDown);
}
public void draw(Graphics g){
g.drawOval(x, y, 60, 60);
}
}
我没有包含导入行,因为我知道我拥有所有正确的模块。编译总是很好,但是当我运行它时圆圈不显示。我在它自己的单独文件中尝试了相同的显示代码,当我运行它时出现了圆圈,那么我在这里做错了什么?