简体   繁体   中英

how do I override awt paint() method correctly

I have a subclass from java.awt.Window . In this subclass I want to override the public void paint(Graphics g) function to draw my own things on it.

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.

But if I call the repaint() method of the object by myself it does not get repainted.

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.

First, you should be using a frame, not a window. Use JFrame , which is what Swing provides for creating frames. Swing is built ontop of AWT, and is pefered for modern development.

Rather than overriding paint(Graphics) of the frame (painting on the frame), you should create a new panel and override it's paint method. It's also recommended to override paintComponent rather than 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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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