call paintcomponent for a jpanel in jframe

陌路散爱 提交于 2019-12-10 21:36:37

问题


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?


回答1:


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
       }

    }
}



回答2:


not clear from your question, but I think that nothing complicated override paintComponent for Swing JComponents, please avoid to use method paint() for Swing JComponents, use only paintComponent()



来源:https://stackoverflow.com/questions/9219762/call-paintcomponent-for-a-jpanel-in-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!