我正在尝试使用GridBagLayout来创建一个包含具有网格布局的JPanel和只有大按钮的JPanel的JFrame。我希望所有行的大小相同,并且JButton的JPanel与一行的大小相同。但是,当前为空的按钮面板约为JFrame的1/3。我不太清楚发生了什么,但是对于我来说维护这个结构非常重要,因为我的其他代码使用了这种结构。任何帮助表示赞赏,并提前感谢您。使用GridBagLayout进行错误的大小调整
这是我的代码:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Minesweeper extends JPanel {
private final int SIZE = 7;
public void startGame(){
JFrame holder = new JFrame();
JPanel window = new JPanel();
JPanel pan = new JPanel();
holder.setLayout(new GridBagLayout());
GridBagConstraints con = new GridBagConstraints();
con.weightx = 1;
con.weighty = 1;
con.gridx = 0;
con.gridy = 0;
con.fill = GridBagConstraints.BOTH;
con.gridheight = SIZE;
con.gridwidth = SIZE;
holder.getContentPane().setBackground(Color.darkGray);
holder.setSize(450, 450);
holder.setResizable(false);
holder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBackground(Color.darkGray);
window.setLayout(new GridLayout(SIZE, SIZE));
for (int c=0; c<(SIZE*SIZE); c++){
int row = (c/SIZE);
int col = (c%SIZE);
JPanel p = new JPanel();
p.setBackground(Color.gray);
Border b = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
p.setBorder(b);
window.add(p);
}
holder.add(window, con);
con.gridx = 0;
con.gridy = SIZE+1;
con.gridheight = 0;
con.gridwidth = SIZE;
holder.add(pan, con);
holder.setVisible(true);
}
public static void main(String[] args){
Minesweeper start = new Minesweeper();
start.startGame();
}
}
这是正在显示的内容:
'JPanel p = new JPanel();'你自己(和用户)一个忙。做那个'JButton p = new JButton();'。我们可以将一个ActionListener添加到一个按钮上,它会响应鼠标点击和键盘操作。按钮还支持图标和/或文本(对空白瓷砖,清除瓷砖,地雷或周围矿井的数量等有用)。 –
我实际上已经写了一个使用jpanels的面板类。目标是扫雷游戏,所以我需要能够更多地操纵它们。 – acn3
*“所以我需要能够操纵他们多一点。”*具体如何?我怀疑面板能做什么,按钮不能。 –