简体   繁体   English

如何正确覆盖awt paint()方法

[英]how do I override awt paint() method correctly

I have a subclass from java.awt.Window . 我有一个java.awt.Window的子类。 In this subclass I want to override the public void paint(Graphics g) function to draw my own things on it. 在这个子类中,我想重写public void paint(Graphics g)函数在其上绘制自己的东西。

The problem is that I dont know how to invoke the repaint correctly. 问题是我不知道如何正确调用重绘。 Everything is implemented and I am sure that it works, because if I open a FileChooser and close it the java.awt.Window repaints and the correct things are shown on it. 一切都已实现,并且我确信它可以正常工作,因为如果我打开FileChooser并将其关闭,则java.awt.Window重新绘制,并在其上显示正确的内容。

But if I call the repaint() method of the object by myself it does not get repainted. 但是,如果我自己调用对象的repaint()方法,则不会重新绘制。

Do you have any idea how I invoke the repaint correctly? 您知道我如何正确调用重绘吗?

public class MyWindow extends java.awt.Window {
    public MyWindows(Window owner) {
        super(owner);
    }
    public void paint(Graphics g) {
        g.fillRect(50,50,50,50);
    }
}

MyWindow window = new MyWindow(owner);
window.repaint(); //this call the paint method but dont show drawn things

I suggest reading the custom painting tutorial provided by Oracle. 我建议阅读Oracle提供的自定义绘画教程

First, you should be using a frame, not a window. 首先,您应该使用框架而不是窗户。 Use JFrame , which is what Swing provides for creating frames. 使用JFrame ,这是Swing提供的用于创建框架的工具。 Swing is built ontop of AWT, and is pefered for modern development. Swing建立在AWT的顶部,并为现代开发而特别重视。

Rather than overriding paint(Graphics) of the frame (painting on the frame), you should create a new panel and override it's paint method. 而不是覆盖框架的paint(Graphics) (在框架上绘画),您应该创建一个新面板并覆盖其paint方法。 It's also recommended to override paintComponent rather than paint : 还建议重写paintComponent而不是paint

class MyPanel extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        //paint
    }
}

You can then add this panel to your frame: 然后,您可以将此面板添加到框架中:

public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
        JFrame frame = new JFrame();
        JPanel panel = new MyPanel();
        panel.setSize(...);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM