I’m having a problem overriding the paint() method in my JPanel subclass, ChordEditor. Even when I override the paint() method, add it to the frame, and call repaint() the paint() method is never called. The printout “entering paint function” does not print. Can anyone help me with this?
My ChordEditor class:
public class ChordEditor extends JPanel{
ArrayList<Chord> chordArray = new ArrayList<Chord>();
public ChordEditor() {
this.repaint();
}
@Override
public void paint(Graphics g) {
System.out.println("entering paint function");
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
Toolkit.getDefaultToolkit().sync();
System.out.println("drawing line");
g2d.drawLine(10, 10, 40, 40);
g.dispose();
}
}
Where I add it to the JFrame:
ChordEditor ce = new ChordEditor();
m_frame.getContentPane().removeAll();
m_frame.add(ce);
m_frame.getContentPane().repaint();
The fact that you issue a
repaintimmediately after you added the component suggests that you do so on an already visible frame. Perhaps you shouldvalidatethe frame first. The following works for me:As already stated in comments to your question, you should override
paintComponentinstead ofpaint, and you should not calldisposeas you didn’t create this Graphics context.The calls to
syncandrepaintshould be unneccessary as well, I guess you added them in an attempt to solve this issue here. So you might remove them once things work for you. You also might consider adding all components to the frame before making it visible. Doing so will cause an implicit validation and is the more common approach to windows with a fixed configuration of controls they contain.