如果在将组件设置为不可见后更改了某些组件,则仅在将组件设置为可见后才重新绘制。这会导致闪烁(旧图形可见几毫秒):
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);
}
}
}
除了在每次将新窗口设置为可见之前创建新窗口,还有其他解决方案吗?
解决了 :)
只需update(getGraphics());
(仅举一个例子):
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();
}
下面是关于之间的差异非常好的信息repaint()
和update(Graphics g)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句