我正在尝试使用箭头键(对于游戏)进行矩形移动,但我收到错误消息。它说这个,但是当我改变它时它仍然不起作用。我已经多次尝试但仍然收到相同的错误。有谁知道为什么会出现这个错误? 这是错误:
java.lang.Error: Do not use javax.swing.JFrame.add() use javax.swing.JFrame.getContentPane().add() instead
at javax.swing.JFrame.createRootPaneException(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Tutorial.main(Tutorial.java:109)
这是我的代码:
// The "Test" class.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Tutorial extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer (5,this);
int x = 0, y = 0, velX = 0, velY = 0;
public Tutorial ()
{
tm.start();
addKeyListener(this);
setFocusable (true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent (Graphics g)
{
super.paintComponent (g);
g.setColor (Color.RED);
g.fillRect (x, y, 50, 30);
}
public void actionPerformed (ActionEvent e)
{
if (x < 0)
{
velX = 0;
x = 0;
}
else if (x > 530)
{
velX = 0;
x = 530;
}
if (y < 0)
{
velY = 0;
y = 0;
}
else if (y > 330)
{
velY = 0;
y = 330;
}
x = x + velX;
y = y + velY;
repaint ();
}
public void keyPressed (KeyEvent e)
{
int c = e.getKeyCode ();
if (c == KeyEvent.VK_LEFT)
{
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1;
}
}
public void keyTyped (KeyEvent e) {}
public void keyReleased (KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main (String arge [])
{
Tutorial t = new Tutorial ();
JFrame jf = new JFrame ();
jf.setTitle ("Tutorial");
jf.setSize (600, 400);
jf.setVisible (true);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
} // Test class