我有一点奇怪的错误。 我写了一些非常小的代码,只显示一个矩形,我可以通过按箭头键移动它。
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(position_x, position_y, 20, size);
}
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
if(code == KeyEvent.VK_UP)
goUp();
else if(code == KeyEvent.VK_DOWN)
goDown();
else if(code == KeyEvent.VK_RIGHT)
goRight();
else if(code == KeyEvent.VK_LEFT)
goLeft();
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void goDown()
{
position_y += 20;
position_x += 0;
}
public void goUp()
{
position_y += -20;
position_x += 0;
}
public void goLeft()
{
position_y += 0;
position_x += -20;
}
public void goRight()
{
position_y += 0;
position_x += 20;
}
每当我调试时,矩形应该直接显示(它有什么作用有时)。但大多数时候,只有一个空白的JFrame。我在另一个系统上尝试过。它也没有在那里工作。
这是我的全部代码。
Main.java
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JFrame;
public class Main
{
private static JFrame frame = new JFrame("Snake");
private static ArrayList<Snake> mySnake = new ArrayList<Snake>();
public static void main(String[] args)
{
frame.setSize(500,500);
frame.setBackground(Color.black);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mySnake.add(new Snake(50, 50, 60, true));
frame.add(mySnake.get(0));
}
}
Snake.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Snake extends JPanel implements KeyListener, ActionListener
{
private static final long serialVersionUID = 1L;
int position_x;
int position_y;
int size;
Timer t = new Timer(500, this);
public Snake(int position_x, int position_y, int size, boolean isAlive)
{
t.start();
this.position_x = position_x;
this.position_y = position_y;
this.size = size;
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(position_x, position_y, 20, size);
}
public void checkSelfEating()
{
}
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
if(code == KeyEvent.VK_UP)
goUp();
else if(code == KeyEvent.VK_DOWN)
goDown();
else if(code == KeyEvent.VK_RIGHT)
goRight();
else if(code == KeyEvent.VK_LEFT)
goLeft();
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void goDown()
{
position_y += 20;
position_x += 0;
}
public void goUp()
{
position_y += -20;
position_x += 0;
}
public void goLeft()
{
position_y += 0;
position_x += -20;
}
public void goRight()
{
position_y += 0;
position_x += 20;
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
是否存在可能存在问题的建议?