Swing重复重绘JComboBox闪烁

时间:2014-04-05 13:57:34

标签: java swing animation repaint

我的动画和JComboBox出现问题。在我的应用程序中,我可以通过使用鼠标和键盘或通过设置动画来移动和转换我的形状。

我的组件层次结构如下:放置在我的JFrame中的JPanel包含一个名为EditorCanvas的面板,其中修改和绘制了形状,以及一个名为DrawMenu的面板,其中包含一些JButton和我的JComboBox。

JFrame - > JPanel - > EditorCanvas
JFrame - > JPanel - > DrawMenu - > JComboBox的

JComboBox用于选择要在单击时添加到画布的形状。 在另一个线程中,我在计算新位置等后每隔10ms在我的画布上调用repaint()...

问题是我不能再使用我的JComboBox了,因为弹出窗口打开后会立即消失。这是由我的重绘引起的。非常奇怪的是我的JComboBox被放置在另一个面板中,因此不应该重新绘制它。

我试图在SwingUtilities.invokeLater调用的Runnable中替换我的重绘调用,但问题仍然存在。

以下是我的代码的一些相关部分:

public class EditorCanvas extends JPanel implements MouseListener, MouseMotionListener, KeyListener {

    ...

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        // To keep keyboard focus
        this.requestFocusInWindow();

        this.graphics = (Graphics2D) g.create();

        this.graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        this.mainRenderer.paintAll(this.graphics);
    }


public class AnimationManager implements Runnable {

    ...

    public void run () {

        try {

            while (Thread.currentThread() == this.thread) {

                // Update time values
                double curTime = System.currentTimeMillis();
                double deltaTime = curTime - this.lastTime;
                this.lastTime = curTime;

                for (Animation anim : this.animations) {
                    anim.update(deltaTime);
                }

                SwingUtilities.invokeLater(new Runnable() {
                    public @Override void run() {
                        EditorParameters.getCanvas().repaint();
                    }
                });

                // Pause the animation if it has to
                synchronized (this) {

                    while (this.pause) {
                        System.out.println("\nAnimation paused!\n");
                        this.wait();
                    }
                }

                Thread.sleep(SLEEP_TIME);
            }

1 个答案:

答案 0 :(得分:1)

  

问题是我不能再使用我的JComboBox,因为弹出窗口会立即消失

绘画方法仅用于绘画。

this.requestFocusInWindow();

你永远不应该在绘画方法中调用这样的方法。

我甚至不知道为什么你需要一个自定义面板。您不应该调用另一个组件的paintAll()方法。 Swing将在绘制面板的所有子组件之后进行绘制。