Reputation: 33
Here is my JFrame class that creates and holds the JPanel that in turn holds the buttons.
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame{
private static final long serialVersionUID = 1L;
private Grid grid;
private SquareButton[][] buttons;
private JPanel board;
public Window(){
super("Territories");
grid=new Grid();
buttons=new SquareButton[8][8];
board=new JPanel(new GridLayout(8, 8));
//Creates each button with proper x and y values and adds each to the board
for (int i=0; i<8; i++){
for (int j=0; j<8; j++){
buttons[j][i]=new SquareButton(j, i);
board.add(buttons[j][i]);
}
}
//Setting some frame properties
setSize(560, 560);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
board.setVisible(true);
add(board);
setVisible(true);
}
}
And here is my JButton class.
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
public class SquareButton extends JButton{
private static final long serialVersionUID = 1L;
private int x, y;
public SquareButton(int x, int y){
super();
this.x=x;
this.y=y;
setPreferredSize(new Dimension(70, 70));
setBorder(BorderFactory.createBevelBorder(0, Color.white, new Color(216, 216, 216)));
setBackground(new Color(247, 247, 247));
setVisible(true);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
Upvotes: 2
Views: 74
Reputation: 208984
It has to do with the fact that you have the methods getX()
and getY()
for your custom button. Every JComponent
(including the subclass JButton
) has a getX and getY already. So when define your own in the SquareButton
, you're ultimately overriding the original methods, which are used for positioning. I'm not exactly sure the order of method calls, but the layout managers uses these methods to determine the laying out the component.
Simply get rid of those methods if you don't need them, or change the names.
An aside: you don't need all the calls the setVisible
on all the components. Calling it on the frame is enough. Also not that you aren't actually adding any special functionality to the button (at least from what you're showing), so it may be preferred to just creating an instance of JButton
and setting its properties, rather than creating custom button class.
Upvotes: 1