我正試圖製作一個程序,使用箭頭鍵在java swing窗口中移動一個圓圈。鍵綁定工作正常,但顯示圓圈總是有問題。這裏是代碼:在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);
}
}
我沒有包括導入行,因爲我知道我有所有正確的模塊。編譯總是很順利,但是當我運行它時,該圓形不顯示。我在它自己的獨立遊戲中嘗試了相同的代碼,當我運行它時出現了這個圈子,那麼我在這裏做錯了什麼?
哪裏畫的叫? – Dodd10x