Paint on panel during runtime

只愿长相守 提交于 2019-12-12 00:48:43

问题


I have a panel on which I want to draw stuff. Painting on it when it is beeing created is no problem.

canvas = new Panel() {
    public void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.drawLine(0, 0, 10, 10);
    }
};

But then I want to draw on it during runtime. By instinct, I've created something like this:

Graphics g = canvas.getGraphics();
g.setColor(Color.GREEN);
g.drawLine(10, 10, 20, 20);
canvas.paint(g);

Sadly, this doesn't work. This is probably a simple question but I cannot find a satisfying result by searching. So how can I do what I want to do?


Sorry for the question above. I just added the paint code on a button click event and it works. It just doesn't work on the windowOpened event of the parent frame. Any ideas why?


回答1:


The problem is that the paint() method can be called at any time whenever the window system (or OS) decides that the particular graphical component needs to be repainted on screen. This may happen at any moment (most often when resizing, moving, switching windows, etc). To see how often it happens just add a log message at the beginning of paint() method. If you paint something on canvas just once it's very likely that it's painted, but then another repaint request comes from OS/window system and your green line gets "overdrawn" by object's paint() . So the answer is that any custom painting should be done in paint(). You can add extra attributes to your subclass (eg. boolean drawGreenLine), check it in paint() and take any appropriate action, eg:

class MyPanel extends JPanel {

    boolean drawGreenLine;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.WHITE);
        g.drawLine(0, 0, 10, 10);
        if (drawGreenLine) {
            g.setColor(Color.GREEN);
            g.drawLine(10, 10, 20, 20);

        }  
    }
};

EDIT: As suggested by @MadProgrammer the example has been changed to override paintComponent(). This way the component is only responsible for drawing itself (and not any children or borders).




回答2:


try g.dispose() to release the GraphicsContext's ressources



来源:https://stackoverflow.com/questions/12562614/paint-on-panel-during-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!