Reusing swing components in Java

If any component was changed after the component was set to invisible, it only redraws AFTER the component is set to visible. This makes it flicker (the old graphics are visible for a few milliseconds):

package test; import javax.swing.*; import java.awt.*; import java.util.logging.Level; import java.util.logging.Logger; class ReusingWindow extends JWindow { JLabel label; public ReusingWindow() { JPanel panel = new JPanel(new BorderLayout()); panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(Color.WHITE); panel.setBorder(BorderFactory.createLineBorder(Color.GRAY)); label = new JLabel("Lazy cat"); label.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); label.setBackground(Color.red); label.setOpaque(true); panel.add(label, BorderLayout.WEST); add(panel); pack(); setLocationRelativeTo(null); } public static void main(String args[]) { ReusingWindow window = new ReusingWindow(); StringBuilder sb = new StringBuilder(); sb.append("<html>"); for (int a = 0; a < 10; a++){ sb.append("Not very lazy cat. Extremelly fast cat.<br>"); } sb.append("</html>"); while (true) { window.label.setText("Lazy cat"); window.setVisible(true); pause(); window.setVisible(false); pause(); window.label.setText(sb.toString()); window.setVisible(true); pause(); window.setVisible(false); pause(); } } private static void pause() { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(ReusingWindow.class.getName()).log(Level.SEVERE, null, ex); } } } 

Is there any solution other than creating a new window every time before setting it visible?

+4
source share
3 answers

Solved :)

Just need update(getGraphics()); (just an example):

 while (true) { window.label.setText("Lazy cat"); window.update(window.getGraphics());//<------ new line window.setVisible(true); pause(); window.setVisible(false); pause(); window.label.setText(sb.toString()); window.update(window.getGraphics());//<------ new line window.setVisible(true); pause(); window.setVisible(false); pause(); } 

Here is very good info on the difference between repaint() and update(Graphics g) .

0
source

The problem may be somewhere with your "reuse window". Using a simple class like

 static class ReusingWindow extends JFrame { JLabel label = new JLabel(); public ReusingWindow() { add(label); setBounds(0, 0, 100, 100); } } 

I do not see the flicker.

0
source

why can't you call

  window.repaint(); 

before calling

  setVisible(true); 

? I can’t reproduce the flicker on my machine. If this does not help, you can try calling

  window.revalidate(); 

and then redraw

0
source

Source: https://habr.com/ru/post/1502369/


All Articles