还原(取消图标化)我的JFrame后,我该如何重画内容? [英] How do I redraw things when my JFrame is restored (deiconified)?

查看:134
本文介绍了还原(取消图标化)我的JFrame后,我该如何重画内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的小JFrame,它带有JToggleButtons和子类化的JPanels,它们知道如何绘制我想要它们绘制的东西.选择一个按钮会使椭圆形出现在相应的面板中.取消选择按钮会使图形消失.

I have a very basic little JFrame with JToggleButtons and subclassed JPanels that know how to draw what I want them to draw. Selecting a button causes an oval to appear in the corresponding panel. Unselecting the buttons makes the drawings disappear.

不幸的是,最小化(图标化)然后还原(去图标化)会导致任何绘制的形状消失.因此,我需要手动触发重绘.问题在于,如果我先显示一个消息框,我只能完成重绘(即,我只能看到它).

Unfortunately, minimizing (iconifying) and then restoring (deiconifying) causes any drawn shapes to disappear. So I need to trigger redrawings manually. The problem is that I can only get the redrawing done (that is, I only see it) if I show a message box first.

这是JFrame的去图标化事件:

Here's the deiconify event for the JFrame:

private void formWindowDeiconified(java.awt.event.WindowEvent evt)
{                                       
    //having this message makes everything work
    JOptionPane.showMessageDialog(null, "Useless message this is.");
    //but if I skip it, I'm SOL
    //what's going on?
    drawAll();
}

此方法遍历我所有的按钮,并在必要时要求重绘:

This method goes over all of my buttons and asks for the redraws when necessary:

public void drawAll()
{
    for (int i=0; i<channels; i++)
    {
        if (buttons[i].isSelected())
        {
            lightboxes[i].drawMe();            
        }
    }
}

这是我的子类JPanel:

and here is my subclassed JPanel:

class MyJPanel extends JPanel {

    public void drawMe()
    {
        Graphics myGraphics = this.getGraphics();
        myGraphics.fillOval(0, 0, this.getWidth(), this.getHeight());    
    }

    public void unDraw()
    {
        this.invalidate();
        this.repaint();
    }
}

推荐答案

首先,为了提高速度,我将使用双缓冲.最好在屏幕上绘制图形,并在绘图完成后将其显示在屏幕上.下面应该可以解决您的问题.

Firstly, for speed I would use double buffering. It's best to paint your graphics off screen and display them to the screen when the drawing has completed. The below should sort you out.

public class MyPanel extends JPanel {
    private BufferedImage buffer;
    private Graphics2D canvas;

    @Override
    public void paintComponent(Graphics g) {
        if(buffer == null) {
            buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            canvas = buffer.createGraphics();
        }
        canvas.fillOval(0, 0, this.getWidth(), this.getHeight());
        g.drawImage(buffer, 0, 0, this);
    }
}

这篇关于还原(取消图标化)我的JFrame后,我该如何重画内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆