gpt4 book ai didi

java - 如何在简单的多线程条件下更新我的 JPanel?

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

有3个线程,每个线程都会向JPanel添加一个JButton,最后3个窗口应该分别有3个Jbutton,但是分别有1个jbutton和2,3个,我尝试使用wait()和notifyAll()方法将 JPanel 更新为 3 个 Jbutton,但失败

(顺便说一句,我对此很陌生,问题源于复杂的 Server_Client 联系人列表问题,我将其简化了很多,如下面的代码)

JFrame example shot

import javax.swing.*;

class TestPanel implements Runnable {
// the common Jpanel of 3 thread
static JPanel SharedPanel = new JPanel();

// the common JFrame of 3 thread
static JFrame SharedFrame = new JFrame();


// the JFrame window x,y position
static int Position = 200;

JButton Button1;
String ButtonName;


public TestPanel(String name) {

// pass a name to JButton
this.ButtonName = name;


}

public static void main(String[] args) throws InterruptedException {

// initializing a "A" named JButton to the common Jpanel
new Thread(new TestPanel("A")).start();


// initializing a "B" named JButton to the common Jpanel

new Thread(new TestPanel("B")).start();

// initializing a "C" named JButton to the common Jpanel

new Thread(new TestPanel("C")).start();

}


@Override
public void run() {
// initializing jbutton
Button1 = new JButton(ButtonName);

// add Jbutton to the static common jpanel
SharedPanel.add(Button1);

//create a new JFrame ,cause 3 window need 3 different jframe (with the same content)
JFrame jf = new JFrame();

// add that common shared japnel the Jframe
jf.add(SharedPanel);

// default initializing of window
jf.setSize(500, 500);

// to prevent overlap window , offset a little bit for better observation
jf.setLocation(Position += 50, Position += 50);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);


}


}

在jpanel中添加新的Jbutton后如何刷新每个窗口?

(我也尝试在 Run() 的末尾分配一个 while 函数,但我发现它没有用,也许我的问题对你来说很简单,谢谢你的帮助!)

最佳答案

调用:

revalidate();

然后

repaint();

在您的共享 JPanel 上将刷新它。

如果您希望刷新所有框架,您可以使用“notifyAll”在框架上调用这些方法。

关于java - 如何在简单的多线程条件下更新我的 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796891/

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