It is inadvisable to override the paint
method of a top level container...
JFrame
contains a number of important layers onto which many other components are placed, buy doing this...
public void paint(Graphics g){
g.drawRect(10,20,30,40);
}
You've successfully stopped any of the child components from begin painted, or in fact, anything other then your rectangle.
(The secret life of a top level swing container - Picture taken from How to use Root Panes)
While some might suggest simple adding a call to super.paint(g)
, I would not recommend it.
Better to use something like the JFrame
's glass pane...This will allow you to paint over the components that reside within the frame. If you need to paint under the components, replace the JFrame
's content pane instead.
You may find...
Of use...
Update
I think I'm beginning to see you problem with trying to perform custom painting on a text area.
The problem is, paintComponent
paints the background AND the text in one foul swoop, meaning that any painting you do before calling super.paintComponent
will be rendered over, but any painting done over it will paint over the text.
You could set the text area to be non-opaque and paint the background yourself...
public class CustomTextArea extends JTextArea {
public CustomTextArea() {
setOpaque(false);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.fillRect(0, 0, 100, 100);
super.paintComponent(g);
}
}
The problem is though, it's easy for people to rest the opaque level and destroy your work. Sure you could override the setOpaque
or getOpaque
, but how do you known when the user actually wants to set the component transparent, so you can stop fill the back ground?