gpt4 book ai didi

java - 线程未运行,为什么 jframe setresizeable 不起作用

转载 作者:行者123 更新时间:2023-11-29 05:52:01 24 4
gpt4 key购买 nike

为什么这个程序不起作用? (它不打印“正在运行...”)

package eu.inmensia.learn;

import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Client extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;
public static final int WIDTH = 300;
public static final int HEIGHT = WIDTH / 16 * 9;
public static final short SCALE = 3;

private Thread thread;
private JFrame frame = new JFrame();
private boolean running = false;

public Client() {
Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
setPreferredSize(size);
}

public synchronized void start() {
running = true;
thread = new Thread("display");
thread.start(); // start the thread
}

public synchronized void stop() {
running = false;
try{
thread.join(); // end the thread
}catch(InterruptedException e){ e.printStackTrace(); }
}

public void run() {
while(running){
System.out.println("Running...");
}
}

public static void main(String[] args) {
Client client = new Client();
client.frame.setResizeable(false);
client.frame.setTitle("Program test");
client.frame.add(client);
client.frame.pack();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setLocationRelativeTo(null);
client.frame.setVisible(true);

client.start();
}
}

我正在尝试学习线程,即使这不是我学过的最难的事情,也是其中之一。 OOP 与此无关 xD

最佳答案

你这样做的方式不对,当您调用 client.start(); 时,它将调用 Client 类中的 start 函数,并在该函数中创建一个具有默认 的线程类的新实例>run 为空的方法

你可能指的是这段代码:

public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start(); // start the thread
}

希望对你有帮助

关于java - 线程未运行,为什么 jframe setresizeable 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13546200/

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