gpt4 book ai didi

java - 变量在静态时发生变化,在非静态时保持不变

转载 作者:行者123 更新时间:2023-12-01 11:38:44 27 4
gpt4 key购买 nike

我有一个在窗口上显示时间的工作类,但唯一的问题是当我将字符串变量设置为非静态时,它们根本不会更新,但是当我将字符串变量设置为静态时,它们会自行更新。我不明白为什么会发生这种情况。代码如下:

public class Test extends Panel implements Runnable {
int second;
int minute;
int hour;
static String second_S = "1";
static String minute_S = "1";
static String hour_S = "1";

static JFrame frame = new JFrame("Clock");
static Test panel = new Test(500, 500, 1);

public static void main(String args[]) throws InterruptedException {
Thread time = new Thread(new Test());

frame.add(panel);
Frame.showFrame(frame);

time.start();

}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);

g.drawString(hour_S, 250, 250);
g.drawString(minute_S, 280, 250);
g.drawString(second_S, 310, 250);

}

public Test() {

second = 0;
minute = 0;
hour = 1;

}

public Test(int width, int length, int minusBy) {
super(width, length, minusBy);
}

@Override
public void run() {
while (true) {
try {
Thread.sleep(1);
second++;
if (second > 60) {
second = 1;
minute++;
}
if (minute > 60) {
minute = 1;
hour++;
}
if (hour > 12) {
hour = 1;
}

hour_S = Integer.toString(hour);
minute_S = Integer.toString(minute);
second_S = Integer.toString(second);

System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
panel.repaint();

} catch (InterruptedException e) {
}
}

}

}

最佳答案

您有两个 Test 实例:

static Test panel = new Test(500, 500, 1); // one which displays the values of the members

public static void main(String args[]) throws InterruptedException {
Thread time = new Thread(new Test()); // and another which updates the variables

frame.add(panel);
Frame.showFrame(frame);

time.start();

}

当您的成员是静态的时,两个实例共享相同的值。当您的成员不是静态时,更新值的实例与显示值的实例不同,并且每个实例都有自己的成员,因此 panel 实例中的实例变量的值仍然存在不变。

如果您使用相同的实例,您的代码将适用于非 staticc 成员:

static Test panel = new Test(500, 500, 1);

public static void main(String args[]) throws InterruptedException {
Thread time = new Thread(panel);

frame.add(panel);
Frame.showFrame(frame);

time.start();

}

关于java - 变量在静态时发生变化,在非静态时保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29733906/

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