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

标签 java multithreading object graphics static

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

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/

相关文章:

java - 如何将 log4j 日志记录从 catalina.out 重定向到单独的文件?

c - Win Api-SetEvent和WaitForSingleObject,线程之间的内存同步

javascript - Javascript中构造对象的两种方式

Javascript 使用 JSON 将对象推送到 cookie

java - 检查 JSONObject 是否包含嵌套值(如果未放置新值)

java - 使用扫描仪读取 .CSV 文件?

linux - 实现提供比线程更好的隔离但性能相当的 Linux 并发原语是否可行?

multithreading - 有没有一种可移植的方式用 Qt 给线程名称?

javascript - 传入对象和数组变量

java - 在运行时观察 application.properties 的变化 Spring boot