所以基本上,我正在做一个游戏任务,我正在尝试创建关键命令。到目前为止唯一不起作用的是addKeyListener(**this**)
。我尝试修复它但最终破坏了我的整个程序。到目前为止我的代码是:
public static void main (String[] args)
throws InterruptedException {
for (int x = 0 ; x < 999 ; x++)
{
int lvl = 0;
int line = 0;
write ();
line = start (line);
for (int p = 0 ; p < 999 ; p++)
{
if (line == 0)
{
System.out.println ("Select a level (1-3)");
lvl = In.getInt ();
if (lvl == 1)
{
JFrame gamu = new JFrame ("Hoops 1.0"); //JFrame that runs a game in a window
Culminating_MingxuanHe ball = new Culminating_MingxuanHe ();
gamu.getContentPane ().add (ball);
gamu.setSize (400, 480); //sets the size for the game
gamu.setVisible (true);
ball.addKeyListener (this);
gamu.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); //closes program when game is closed
while (true)
{
ball.moveBall (); //runs the methods
ball.repaint ();
Thread.sleep (8); //speed of the square
}
}
}
}
if (line == 1)
{
System.out.println ("Goodbye, have a nice day");
x = 999;
}
}
}
int a = 200, s = 1, d = 100, f = 1; //initial position of the square
int q = 150, w = 430, e = 80, r = 10;
int plat = 149;
int plat2 = 81;
int mov = 10;
public void moveBall ()
{
if (a + s < 0) //border on left
s = 1;
if (a + s > getWidth () - 25) //border on right
s = -1;
if (d + f < 0) //border on top
f = 1;
if (d + f > getHeight () - 25) //border on bottom
f = -1;
a = a + s; //moves the ball
d = d + f;
}
public void KeyboardExample ()
{
KeyListener listener = new keyPressed ();
addKeyListener (listener);
setFocusable (true);
}
public void keyPressed (KeyEvent e)
{
int key = e.getKeyCode ();
if (key == KeyEvent.VK_LEFT)
{
plat = plat - mov;
}
if (key == KeyEvent.VK_RIGHT)
{
plat = plat + mov;
}
}
public void keyTyped (KeyEvent e)
{
}
public void keyReleased (KeyEvent e)
{
}
}
答案 0 :(得分:0)
您正在尝试访问对象的实例。你不能那样做,因为main方法是静态的。静态方法是CLASS的一部分,实例方法是OBJECT的一部分。你在代码中所做的是尝试访问你曾经称之为main的对象(即variable.main),但它没有用,因为没有对象。希望这有助于:)
答案 1 :(得分:0)
这种格式适用于在Java SE中保持Swing内容的整洁。
class YourClass extends JFrame {
// variables or constants required for the frame
public YourClass() {
/*
set frame properties, add listeners, and here 'this' (referring to the YourClass instance) will work since its in a non static context
*/
}
/*
add methods to be executed when events are triggered according to the listener specified in the above constructor
*/
}
public class TestClass {
/*
here goes your main method and create the instance of the YourClass class and call setVisible(true)
*/
}