简体   繁体   中英

call paintcomponent for a jpanel in jframe

I have a JFrame with a JPanel on it ( JPanel is private in JFrame ). Now I want to override JPanel by using paintComponent method.

How can I do that?

When you create your instance of JPanel , (assuming you're doing it this way), do this:

JPanel panel = new JPanel(){
    @Override
    public void paintComponent(Graphics g){
       // paint code
    }
};

The other alternative is to create a private class which extends JPanel .
For example:

public class OuterClass{
    // fields, constructors, methods etc..

    private class MyPanel extends JPanel{   
       // fields, constructors, methods etc..

       @Override
       public void paintComponent(Graphics g){
          // paint code
       }

    }
}

从你的问题不清楚,但我认为没有什么复杂的覆盖了Swing JComponents的paintComponent ,请避免使用方法paint()Swing JComponents ,只使用paintComponent()

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