4

如果在组件设置为不可见后更改了某些组件,则仅在组件设置为可见后才重新绘制。这会使闪烁(旧图形可见几毫秒):

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);
        }
    }
}

除了每次在设置可见之前创建新窗口之外,还有什么解决方案吗?

4

3 回答 3

0

Solved :)

Just need to 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 about the difference between repaint() and update(Graphics g).

于 2013-09-16T18:31:46.027 回答
0

你为什么不能打电话

    window.repaint(); 

调用前手动

   setVisible(true); 

? 我无法在我的机器上重现闪烁.. 如果这没有帮助你可以尝试打电话

   window.revalidate(); 

以及重绘前

于 2013-09-16T09:35:23.710 回答
0

问题可能出在您的“重用窗口”上。使用简单的类

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

我没有观察到任何闪烁。

于 2013-09-16T09:28:32.597 回答