I am new to Java, and the whole working with arrays + using classes and their methods to populate and display the arrays. I have spent the last 2-3 hours, working on this and checking google for various answers and none have seemed to help, I am still stuck. I don’t really know how to use the methods from the rectangle1 class, when using arrays.
Main class:
public static void main(String[] args) {
GameBoard frame = new GameBoard();
}
GameBoard Class
public class GameBoard extends JFrame {
public GameBoard() {
JFrame frame = new JFrame();
frame.setBounds(0, 0, 195, 215);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rectangle1 board[][] = new Rectangle1[3][3];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = new Rectangle1(0, 0, 195, 215);
if ((row + col) % 2 == 0) {
Graphics g = null;
board[row][col].paint(g);
g.setColor(Color.yellow);
g.fillRect(0, 0, 195, 215);
} else {
Graphics h = null;
board[row][col].paint(h);
h.setColor(Color.red);
h.fillRect(0, 0, 195, 215);
}
frame.add(board[row][col]);
}
}
}
}
Rectangle1 class.
public class Rectangle1 extends JComponent {
/** post: getX() == x and getY() == y
* and getWidth() == w and getHeight() == h
* and getBackground() == Color.black
*/
public Rectangle1(int x, int y, int w, int h) {
super();
setBounds(x, y, w, h);
setBackground(Color.black);
}
/** post: this method draws a filled Rectangle
* and the upper left corner is (getX(), getY())
* and the rectangle's dimensions are getWidth() and getHeight()
* and the rectangle's color is getBackground()
*/
public void paint(Graphics g) {
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth()-1, getHeight()-1);
paintChildren(g);
}
}
Firstly, you are fighting the layout manager, calling something like
setBounds(x, y, w, h)in youRectangleclass is going to overridden by the layout manager of the parent container (the frame in this case)Secondly, you are not responsible for painting, do this;
…is wrong. If it doesn’t end up with you programming crashing, then your lucky.
While I try and figure out a solution, you might like to take some time and read through
While on my rant…
This;
public void paint(Graphics g) {
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth()-1, getHeight()-1);
paintChildren(g);
}
is inappropriate. You MUST call
super.paint(), there’s to much going on in the background for you to override this method without calling it’ssuper.In fact, you should avoid overriding
paintwhere ever possible and userpaintComponentinstead.Also, coordinates in Swing are relative to the component. That is, the top/left corner of any component (within the context of the component) is always 0x0
Here’s a working example
Because of the nature of your requirements, I’ve been forced to use
GridBagLayoutwhich is not the simplest of layout managers to use.JComponentsare transparent by nature and you are required to fill them, better to useJPanel