Reputation: 101
There are 3 threads , every thread will add a JButton to JPanel , and the final 3 window should have 3 Jbuttons respectively , but 1 jbutton and 2,3 respectively , i try to use wait() and notifyAll() method to update JPanel to 3 Jbuttons , but failed
(BTW,i am new to this , the problem originated from a complex Server_Client contact list matter ,i simplify it a lot like below codes)
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);
}
}
How to refresh each window after a new Jbutton was add to jpanel?
(i also try to assign a while function in the end of Run(),but i discover it is useless, maybe my question is easy for you , thanks for your good help !)
Upvotes: 1
Views: 470
Reputation: 543
calling:
revalidate();
and then
repaint();
on your shared JPanel will refresh it.
If you wish to refresh all frames you can call those methods on the frames with "notifyAll".
Upvotes: 1