Link to home
Start Free TrialLog in
Avatar of sgalzin
sgalzin

asked on

Paint all the JComponents that are in a JPanel

Hi,

I have two classes : AJPanel (extends JPanel) and AJComponent (extends JComponent). The AJPanel constructor adds 10 AJComponent objects to the panel :

 public AJPanel () {
  this.setLayout ( new java.awt.BorderLayout () );
  for ( int i = 0; i < 10; i ++ ) {
   this.add ( new AJComponent () );
  }      

The problem is these components are not drawn on the screen. So I tried overwriting the AJPanel.paintComponent method like this :

 public void paintComponent ( Graphics g ) {
  super.paintComponent ( g );
  for ( int i = 0; i < this.getComponentCount (); i ++ ) {
   this.getComponent ( i ).setLocation ( new Point ( i*5 + 10, i*5 + 10 ) );
   System.out.println ( "theX : " + this.getComponent ( i ).getX () );
   this.getComponent ( i ).update ( g );
  }
 }

And I added some code for debugging purposes to the AJComponent.paintComponent method :

 public void paintComponent ( Graphics g ) {
  System.out.println ( "myX : " + this.getX () );
// ... the rest of the painting code
 }

However, this is what the output is like :

theX : 10
theX : 15
theX : 20
theX : 25
theX : 30
theX : 35
theX : 40
theX : 45
theX : 50
theX : 55
myX : 55
myX : 55

Whereas I was expecting something like :

theX : 10
myX : 10
theX : 15
myX : 15
theX : 20
myX : 20
theX : 25
myX : 25
...
theX : 55
myX : 55


What is going wrong ? How can I paint all the components of the AJPanel ? Currently, only the last one is painted.

Thanks,

Stephane.
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sgalzin
sgalzin

ASKER

wow ! that worked like magic ... Thanks a lot,

Stephane.

PS : if you could give me a word of advice, a link, or any information concerning these layouts I'd be very grateful : this is the second problem I have with layouts and I might be missing some important basic information ...
Unfortunately, there's loads of them... http://www.softbear.com/people/larry/javalm.htm

I always tend to use BorderLayout http://java.sun.com/docs/books/tutorial/uiswing/layout/border.html

The best resource for the standard ones is the sun site:

http://java.sun.com/docs/books/tutorial/uiswing/layout/

But as I said, there are loads of third party ones, and more all the time...

http://www.clientjava.com/blog/2004/11/01.html

for example is a new one that looks quite cool :-)

I'd stick with Grid, Border and Flow till you get used to them though...then branch out :-)

Tim
Avatar of sgalzin

ASKER

Thanks so much,

Stephane.
No worries :-)

Good luck!

Tim