问题
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