我正在尝试制作一个简单的游戏,你可以设置构成凯尔特人设计的瓷砖,而我似乎无法使按钮保持相同的尺寸。这是代码:
public class CTGContent {
public static JPanel content = new JPanel();
private static JButton board[][] = new JButton[20][20];
static private Random random = new Random();
public static int CTGcolumn = random.nextInt(14)+1;
public static int CTGRow = 15;
private static GridLayout boardLayout;
public final int getBoardWidth(){
return CTGcolumn*40;
}
public final int getBoardHeight(){
return CTGRow*40;
}
public static void initializeBoard(){
int row = 0;
int column = 0;
int defaultCOL = 0;
int defaultROW = 0;
boardLayout = new GridLayout(CTGRow, CTGcolumn);
content.setLayout(boardLayout);
Random determine = new Random();
while (row < CTGRow){
column = 0;
while (column < CTGcolumn){
board[row][column] = new JButton(new ImageIcon("images\\template.gif"));
board[row][column].setPreferredSize(new Dimension(40, 40));
board[row][column].setMaximumSize(new Dimension(40, 40));
board[row][column].setMinimumSize(new Dimension(40, 40));
content.add(board[row][column]);
column++;
}
row++;
}
}
private static void build(){
initializeBoard();
JFrame window = new JFrame("testing the menubar");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(content);
content.add(new JLabel("My Label"));
window.pack();
window.setVisible(true);
}
public CTGContent() {
}
public CTGContent(JFrame window){
initializeBoard();
window.add(content);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
build();
}
});
}
}
它通常从正确的尺寸开始但是由于某种原因,如果我调整窗口大小或者用它改变大小的东西。无论怎样,我都需要它们保持相同的尺寸。我怎么能这样做?
答案 0 :(得分:3)
变化:
window.setContentPane(content);
要:
JPanel contentCenter = new JPanel(new GridBagLayout());
contentCenter.add(content);
window.setContentPane(contentCenter);
还有其他方法可以做到这一点,例如将布局设为FlowLayout
,但GBL会使其保持良好的居中 - 垂直和水平。
答案 1 :(得分:0)
您使用GridLayout
因为您的按钮水平/垂直调整大小总是填充整个网格单元格。为了防止您使用其他LayoutManager
,例如GridBagLayout
。