Java – redraws JPanel only after window resizing is complete
I have a JPanel and I draw four rectangles on it Randomly select the color of each of these rectangles The color changes only when the user clicks a specific rectangle
The problem is that when the user resizes the window, everything on the JPanel will repeat "redraw" This causes the rectangle to change color quickly
Ideally, when resizing, I need the color of the rectangle to remain the same Otherwise, I can also use a solution to redraw JPanel only once after resizing
Do you have any general ideas on how I can achieve this? If there are onstartresize and onfinishresize callback methods in componentlistener, I think it will be much easier
thank you!
Solution
This example can be used to illustrate violations referenced by @ Kleopatra When resizing a component, the event scheduling mechanism can help you call repaint() If you change the state you are rendering, such as in paintcomponent (), you will see it loop quickly In the following example, the bottom row flashes while the top row remains unchanged
Appendix: animationtest is a related example, which uses this effect to execute animation in componentadapter
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** @https://stackoverflow.com/questions/7735774 */ public class ResizeMe extends JPanel { private static final int N = 4; private static final int SIZE = 100; private static final Random rnd = new Random(); private final List<JLabel> list = new ArrayList<JLabel>(); private boolean randomize; public ResizeMe(boolean randomize) { this.randomize = randomize; this.setLayout(new GridLayout(1,0)); for (int i = 0; i < N; i++) { JLabel label = new JLabel(); label.setPreferredSize(new Dimension(SIZE,SIZE)); label.setOpaque(true); list.add(label); this.add(label); } initColors(); this.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { System.out.println(e); } }); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (randomize) { initColors(); } } private void initColors() { for (JLabel label : list) { label.setBackground(new Color(rnd.nextInt())); } } private static void display() { JFrame f = new JFrame("ResizeMe"); f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new GridLayout(0,1)); f.add(new ResizeMe(false),BorderLayout.NORTH); f.add(new ResizeMe(true),BorderLayout.soUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokelater(new Runnable() { @Override public void run() { display(); } }); } }