简体   繁体   中英

How do I draw something in a JPanel after I already called the paintComponent method

I'm new to making GUIs in Java. As I understand, there's a class called Graphics which is in charge of drawing shapes in a JPanel. When my application starts, I call the paintComponent method, which draws the board of the game I'm programming, and the paintComponent method takes a Graphics g as input. However, later on, I want to update the board, so how do I tell the same g that drew the board at the start of the game to draw something else when the user does something like clicking?

I believe this should have a very simple answer.

Every JComponent (Swing component) has a repaint() method, just call it to tell the DrawingManager to redraw your component.

All your drawing code should be in paintComponent method, that means that you don't draw anything anywhere else (you draw only in the flow of invocation of paintComponent , you can have drawing code structured in methods of course).

This method needs to have access to the state that indicates what and where should be drawn. It is because the OS could request repainting, and then only the painting methods from JComponent are called.

When you invoke repaint() on your JComponent , then in short time the paintComponent() method of the component on which you requested repainting will be called by the drawing thread, and you should draw only in this drawing thread.

尝试repaint()或revalidate(),它应该可以工作。

I call the paintComponent method

No, you should never call the paintComponent() method directly. Swing will call the method for you when the component needs to be repainted.

I want to update the board

Then you need a "setter" method. Think of other Swing components. They have methods like "setForeground(), setBackground(), setText()" etc.

So if you want to change your component then you need to create appropriate setter method to change the properties of your class. Then in the method you save the property and simply invoke repaint() and Swing will repaint your component. So now your paintComponent() method needs to check the property you just set to do the appropriate painting.

public void setSomeProperty(Obect someProperty)
{
    this.someProperty = someProperty;
    repaint();
}

....

protected void paintComponent(Graphics g)
{
    super.paintComponent();

    //  paint the board

    if (someProperty != null)
        // paint the property
}

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