JTabbedPane swing update error

I have 2 JPanels in JTabbedPane, and when update (g) is called on the panel inside the first panel (its animation), even if the second panel is the selected panel (i.e. the one you see), the updated panel appears on the screen. Why is this and how can I get around this behavior?

+2
source share
2 answers

update() JComponent "does not clear the background", so you may need to do this explicitly. Typical JTabbedPane examples JTabbedPane usually not necessary to use update() . Maybe sscce showing that your use may help.

Addendum 1: It is not clear why you are calling update() . Below is a simple animation that does not detect anomalies.

Addendum 2: See Painting in AWT and Swing: paint () vs. update () . Instead, you can use repaint() in actionPerformed() .

enter image description here

 import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class JTabbedTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { //@Override public void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTabbedPane jtp = new JTabbedPane(); jtp.setPreferredSize(new Dimension(320, 200)); jtp.addTab("Reds", new ColorPanel(Color.RED)); jtp.addTab("Greens", new ColorPanel(Color.GREEN)); jtp.addTab("Blues", new ColorPanel(Color.BLUE)); f.add(jtp, BorderLayout.CENTER); f.pack(); f.setVisible(true); } }); } private static class ColorPanel extends JPanel implements ActionListener { private final Random rnd = new Random(); private final Timer timer = new Timer(1000, this); private Color color; private int mask; private JLabel label = new JLabel("Stackoverflow!"); public ColorPanel(Color color) { super(true); this.color = color; this.mask = color.getRGB(); this.setBackground(color); label.setForeground(color); this.add(label); timer.start(); } //@Override public void actionPerformed(ActionEvent e) { color = new Color(rnd.nextInt() & mask); this.setBackground(color); } } } 
+5
source

when update (g) is called on a panel inside the first panel (its animation)

Overriding the update method (...) is an old AWT trick and should never be used with Swing.

Read the section in the Swing tutorial on Custom Painting for the right way to do this. And for animation, read "How to use a swing timer," which is also contained in the tutorial.

+2
source

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


All Articles