我需要使用gridlayout和jlabels在jpanel中制作一个棋盘。所以现在工作正常。但我的主窗口仅显示调整大小时的组件。
问题是,如何让我的JPanel使用标签图块的大小,然后让Jframe使用我的JPanel的大小?
以下是代码:
public class MainWindow extends JFrame {
public MainWindow(){
super();
this.setLayout(new BorderLayout());
this.setLocationRelativeTo(null);
addNewGameArea();
this.pack();
this.setVisible(true);
}
private void addNewGameArea(){
GameArea game = new GameArea();
this.add(game, BorderLayout.CENTER);
}
}
另一堂课:
public class GameArea extends JPanel {
public GameArea(){
super();
this.setLayout(new GridLayout(10,10));
addLabels();
//this.setPreferredSize(this.getPrefferedSize());
this.setVisible(true);
}
//Creates a 2D JLabel array
private JLabel[][] createLabel(){
JLabel[][] labelarray= new JLabel[10][10];
for (int i=0;i < 10;i++){
for (int j = 0; j < 10; j++){
labelarray[i][j] = new JLabel();
}
}
return labelarray;
}
// Color the labels alternating black and white
private void colorLabels(JLabel[][] labelAr){
//Here i set the color of the tiles, set them opaque and set the size to (50, 50)
}
// add the labels to the Panel
private void addLabels(){
JLabel[][] labels = createLabel();
colorLabels(labels);
for (int i=0;i<10;i++){
for (int j = 0; j < 10; j++){
this.add(labels[i][j]);
}
}
}
}
在我的主要内容中,我只需创建一个新的MainWindow。
PS:当我为MainWindow设置特定尺寸(500,500)时,一切都显示出来。但我希望它能自动适应子组件。
编辑:在发布时它看起来像这样:
编辑:主要
public class StartGui {
public static void main (String[] args){
MainWindow mw = new MainWindow();
}
}