BaconMan97
BaconMan97

Reputation: 67

Re-painting using PaintComponent()

class BiomeViewComponent extends JComponent {
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int xpos=300;
    int ypos=300;
    g.setColor(Color.yellow);
    Random r = new Random();
    int spread = r.nextInt(2)+1;
    System.out.println(spread);
    if (spread==1){
        xpos=xpos+50;
        g.setColor(Color.yellow);
        g.fillRect(xpos,ypos,50,50);
    }
    else{
        ypos=ypos-50;
        g.setColor(Color.yellow);
        g.fillRect(xpos,ypos,50,50);
    }
}

}

I used the accepted answer of the paintComponent script like the above code and it worked but the question now is how do i make it paint more than once?

Upvotes: 1

Views: 139

Answers (1)

mikera
mikera

Reputation: 106401

You should write your painting code inside an overriden paintComponent function, something like:

class BiomeViewComponent extends JComponent {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // your painting code goes here
    }
}

And then add this to your JFrame with something like:

JFrame j = new JFrame();
BiomeViewComponent bv=new BiomeViewComponent();

Container c=j.getContentPane();
c.setLayout(new BorderLayout()); // whatever layout you want here.....
c.add(bv);

The BiomeViewComponent will get repainted by Swing whenever needed (i.e. it will call the paintComponent(..) function for you)

Note that it's good practice to put your painting code inside a component other than the JFrame - this gives you flexibility to reposition the viewing component as needed withing the JFrame as you build up your GUI.

Upvotes: 2

Related Questions