Mahdi_Nine
Mahdi_Nine

Reputation: 14751

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?

Upvotes: 3

Views: 3574

Answers (2)

rtheunissen
rtheunissen

Reputation: 7435

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
       }

    }
}

Upvotes: 4

mKorbel
mKorbel

Reputation: 109813

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()

Upvotes: 2

Related Questions