gpt4 book ai didi

java - 从类到类访问变量

转载 作者:行者123 更新时间:2023-12-01 19:09:05 25 4
gpt4 key购买 nike

如何从另一个类访问某些变量?例如,我有 2 个文件:

Main.java

package keyboardgame;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends Applet implements KeyListener
{

private static final long serialVersionUID = 1L;
private static boolean keyboardRightPressed = false;
private static boolean keyboardLeftPressed = false;
private static boolean keyboardUpPressed = false;
private static boolean keyboardDownPressed = false;

int ballX = 20;
int ballY = 20;
int ballSpeed = 10;

public void init()
{
addKeyListener(this);
}

public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboardRightPressed = true;
ballX = ballX + ballSpeed;
repaint();
}

if(keyCode == KeyEvent.VK_LEFT)
{
keyboardLeftPressed = true;
ballX = ballX - ballSpeed;
repaint();
}

if(keyCode == KeyEvent.VK_UP)
{
keyboardUpPressed = true;
ballY = ballY - ballSpeed;
repaint();
}

if(keyCode == KeyEvent.VK_DOWN)
{
keyboardDownPressed = true;
ballY = ballY + ballSpeed;
repaint();
}
}

public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
keyboardRightPressed = false;
repaint();
}

if(keyCode == KeyEvent.VK_LEFT)
{
keyboardLeftPressed = false;
repaint();
}

if(keyCode == KeyEvent.VK_UP)
{
keyboardUpPressed = false;
repaint();
}

if(keyCode == KeyEvent.VK_DOWN)
{
keyboardDownPressed = false;
repaint();
}
}

public void keyTyped(KeyEvent e) {
}


public void paint(Graphics g)
{
g.fillOval(ballX,ballY,20,20);
g.drawString("Right :"+keyboardRightPressed,0,10);
g.drawString("Left :"+keyboardLeftPressed,0,20);
g.drawString("Up :"+keyboardUpPressed,0,30);
g.drawString("Down :"+keyboardDownPressed,0,40);
}

}

KeyThread.java

package keyboardgame;

public class KeyThread implements Runnable
{

public KeyThread(String s,int speed)
{
name = s;
time = speed;
}

public void run()
{
try
{
if(keyboardRightPressed == true)
{
ballX = ballX + 10;
ballY = ballY + 10;
}
}
catch(Exception e)
{

}
}
}

我想要的是从KeyThread.java能够修改/增加/访问Main.java的值,尤其是

int ballX = 20; 
int ballY = 20;

这样我就可以从 Main.java 调用我的线程,就像

Thread t5 = new Thread(new KeyThread("Moving Right", ballX = ballX + 1, 20));
t5.start();

我怎样才能做到这一点?为什么这么难做到?

最佳答案

为了调用对象的非静态方法,您需要该类的实例。欲了解更多信息,请参阅Objects .

关于java - 从类到类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8885976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com