I am trying to create a program with 2 JPanel
using BorderLayout
. The center panel is for random drawing of rectangle while the south panel is for
You're not calling super.paintComponent
protected void paintComponent(Graphics g) {
super.paintComponent(g); // <-- Insert me here and watch problem go away
RandomX();
RandomY();
g.setColor(RandomColour());
g.fillRect(x, y, xSize, ySize);
try {
Thread.sleep(50); // <-- This is an INCREDIBLY bad idea, NEVER, EVER do this
} catch (InterruptedException e) {
}
repaint(); // <-- This is a bad idea, watch CPU max out...
}
You are obligated to call super.paintComponent
to ensure that the paint chain is upheld correctly and things like opacity and cleaning up of the graphics context takes place.
The Graphics
object is shared between components through a single repaint pass, failure to honor the correct paint chain will result in, well, problems like yours
Never update the UI in anyway from any paint
method (this includes calling repaint
), this is just causing your paint
method to be recalled, over and over and over...until you CPU hits 100% and program hangs.
Never, EVER do any time consuming or block operations within the paint
methods (or the UI generally), this will make it look like the program as hung and make the users upset (you think zombi hordes are bad :P). Blocking in this way prevents the EDT from responding to paint requests...
I'd recommend having a read through: