tags:

views:

35

answers:

2

I'm not used to GUI development, but now I need it a little bit, and I want to avoid reading all documentation just because of this problem.

I'm having trouble displaying a custom component like the one I posted below. If I add it to a JFrame it works fine, but I cant add more then one, and if I add it to a JPanel it wont be displayed at all.

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;

public class Test extends JComponent implements Runnable {

    private int c,x,y;

    public Test(int x,int y){
        c = 0;
        this.x = x;
        this.y = y;
    }

    private void inc(){
        c++;
        if(c>255){
            c = 0;
        }
    }

    public void paint(Graphics g) {
        g.setColor(new Color(c,c,c));
        g.fillRect(x, y, 50, 50);
    }

    public void run() {
        while(true){
            inc();
            try{
                Thread.currentThread().sleep(20);
            } catch (Exception e){
            }
            repaint();
        }
    }
}
+1  A: 

As a bare minimum, you should also setPreferredSize(x+50, y+50) and setMininumSize(x+50, y+50) in the constructor to let layout manager know about your component's size for placing it in the container widget properly.

Also, calling repaint() not from AWTEventThread is quite bad. Use SwingUtilities.invokeLater() for that.

Vanya
+2  A: 

and I want to avoid reading all documentation just because of this problem.

Yes, well reading actually saves time because you do things correctly the first time and you don't have to sit around waiting/hoping someone answers your question.

So start with the Swing tutorial

1) Custom painting is done by overriding the paintComponent() method. Read the section from the Swing tutorial on "Custom Painting".

2) Animation should be done by using the Swing Timer, see the section from the tutorial on "How to Use Timers".

3) In fact you don't event need to create a custom component. All you need to do is create a JPanel, set its preferred size, and then use a Timer to change its background.

camickr
The only difference between JComponent and JPanel is that latter paints it's background... So it doesn't really matter so much, what to extend :-)
Vanya