so i’m trying to set up an application where i have multiple panels inside a jframe. lets say 3 of them are purely for display purposes, and one of them is for control purposes. i’m using a borderLayout but i don’t think the layout should really affect things here.
my problem is this: i want the repainting of the three display panels to be under the control of buttons in the control panel, and i want them to all execute in sync whenever a button on the control panel is pressed. to do this, i set up this little method :
public void update(){
while(ButtonIsOn){
a.repaint();
b.repaint()
c.repaint();
System.out.println("a,b, and c should have repainted");
}
}
where a,b, and c are all display panels and i want a,b,and c to all repaint continously until i press the button again. the problem is, when i execute the loop, the message prints in an infinite loop, but none of the panels do anything, ie, none of them repaint.
i’ve been reading up on the event dispatch thread and swing multithreading, but nothing i’ve found so far has really solved my problem. could someone give me the gist of what i’m doing wrong here, or even better, some sample code that handles the situation i’m describing? thanks…
The java.util.concurrent package provides very powerful tools for concurrent programing.
In the code below, I make use of a
ReentrantLock(which works much like the Javasynchronizedkeyword, ensuring mutually exclusive access by multiple threads to a single block of code). The other great thing whichReentrantLockprovides areConditions, which allowThreadsto wait for a particular event before continuing.Here,
RepaintManagersimply loops, callingrepaint()on theJPanel. However, whentoggleRepaintMode()is called, it blocks, waiting on themodeChanged ConditionuntiltoggleRepaintMode()is called again.You should be able to run the following code right out of the box. Pressing the
JButtontoggle repainting of theJPanel(which you can see working by theSystem.out.printlnstatements).In general, I’d highly recommend getting familiar with the capabilities that java.util.concurrent offers. There’s lots of very powerful stuff there. There’s a good tutorial at http://docs.oracle.com/javase/tutorial/essential/concurrency/