Skip to main content

Adding more than one instance of extended JComponent class

1 reply [Last post]
cikabole
Offline
Joined: 2009-06-11

Hello,
I trying to write application which display two dimensional Array of rectangles in GUI. My idea was to write class who extends JComponent class which will just draw rectangle on JFrame for every instance object of that class and on that way I want to draw a grid. Depending on reference array, every object will be filled with color or "empty" rectangle.
In next code fragment I trying to do this, and 'everything' working just fine except drawing rectangle. Problem is that his code drawing only last instance of created array of "GUIKolonija" objects.

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class GUIIgre {
public static void GUI(){

JFrame prozor=new JFrame("Game of life");
JButton btnNext= new JButton("Next generation");
JButton btnStart= new JButton("Start");
GUIKolonija[][] guiKolonija;
guiKolonija = new GUIKolonija[10][10];
prozor.setSize(409, 500);
prozor.setLocationByPlatform(true);
prozor.add(btnNext);

for(int y=0; y<=10;y++)
for(int x=0; x<=10;x++){
guiKolonija[x][y]=new GUIKolonija();
guiKolonija[x][y].setKoordinate(x, y);
prozor.add(guiKolonija[x][y]);
}
// prozor.add(guiKolonija[0][0]);

btnNext.setBounds(40, 430, 150, 30);
btnStart.setBounds(220, 430,150,30);

// prozor.add(btnStart);

prozor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prozor.setVisible(true);
}
}

class GUIKolonija extends JComponent{
private int x;
private int y;

public void paint(Graphics graf){
graf.setColor(Color.BLUE);
graf.drawRect(x*20, y*20, 20, 20);
}
public void setKoordinate(int x, int y){
this.x = x;
this.y = y;
}

How i can display whole code?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
cikabole
Offline
Joined: 2009-06-11

How I can display whole code?