有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);
}
}
在将新的Jbutton添加到jpanel后,如何刷新每个窗口?
(我也尝试在Run()的末尾分配一个while函数,但我发现它没有用,也许我的问题对您来说很容易,感谢您的大力帮助!)
最佳答案
致电:
revalidate();
然后
repaint();
在共享的JPanel上将刷新它。
如果希望刷新所有框架,则可以使用“ notifyAll”在框架上调用这些方法。