运行期间烤漆面板上 [英] Paint on panel during runtime

查看:246
本文介绍了运行期间烤漆面板上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有哪些我想提请东西的面板。
它画的是beeing创建时是没有问题的。

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?

抱歉上面的问题。
我只是增加了一个按钮单击事件油漆code和它的作品。
它只是不父帧的windowOpened事件工作。
任何想法,为什么?

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?

推荐答案

的问题是,该涂料()方法可以在任何时间被调用每当窗口系统(或OS)决定该特定图形组件需要被重新绘制在屏幕上。 (调整时,移动,切换窗口等最常见),这可能在任何时刻发生。要了解往往只可能出现在paint()方法的开头添加日志信息。如果您在画布上画东西只是一次它很可能,它的画,但随后又重绘请求来自OS /窗系统和绿线被透支的对象的paint()方法。
因此,答案是,任何自定义的绘画应该油漆()来完成。你可以额外的属性添加到您的子类(如布尔drawGreenLine),检查油漆(),并采取适当的行动,例如:

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

        }  
    }
};

编辑:如由@MadProgrammer提出的实施例已被更改为重写paintComponent()。这样,组件仅绘制本身(而不是任何儿童或边框)负责。

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).

这篇关于运行期间烤漆面板上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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