java - 如何在简单的多线程条件下更新我的 JPanel?
问题描述
有3个线程,每个线程都会向JPanel添加一个JButton,最后3个窗口应该分别有3个Jbutton,但分别有1个jbutton和2,3个,我尝试使用wait()和notifyAll()方法来更新JPanel 3 个 Jbuttons ,但失败了
(顺便说一句,我是新手,问题源于复杂的 Server_Client 联系人列表问题,我将其简化为如下代码)
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);
}
}
将新的 Jbutton 添加到 jpanel 后如何刷新每个窗口?
(我也尝试在 Run() 的末尾分配一个 while 函数,但我发现它没用,也许我的问题对你来说很容易,谢谢你的帮助!)
解决方案
调用:
revalidate();
接着
repaint();
在您共享的 JPanel 上将刷新它。
如果您希望刷新所有帧,您可以使用“notifyAll”在帧上调用这些方法。
推荐阅读
- java - 滚动视图顶部的静态按钮 android studio
- python - 如何使用变量列表循环函数?
- javascript - Javascript:函数前的 $ 是什么意思?
- php - Laravel hasmanythrough 或 mysql groupby
- regex - 使用 sed \t 时列未对齐
- c++ - 如何理解句子其生命周期始于对 e 的评价
- python - tensorflow“没有足够的内存资源来处理这个命令”。这是什么意思?- Python v3.8
- python - 错误无法以只读模式创建组
- java - 如何根据变量找到id?
- java - Spring Boot 不加载 application.properties