使用GridBagLayout的带按钮的java填充框架
我试图建立一个匹配的游戏,每个按钮上都有图标。虽然,这还没有接近完成,但我在用按钮填充面板时遇到了一个问题
通过这个代码,我得到了一个灰色的框架。如果我在“//execution”下注释掉我使用的3种方法,面板将全部为黑色(这就是我测试按钮是否填充空间的方式)
因为某些原因,我的按钮没有被填充到面板上
我需要一些帮助!!!我哪里做错了
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MemoryMainFrame extends JFrame implements ActionListener {
JButton button[] = new JButton[16];
private static final int SIXTEEN_BUTTONS = 16;
JPanel mainPanel = new JPanel();
double dim = Math.sqrt(SIXTEEN_BUTTONS);
int numOfColumns = (int) (dim);
int numOfRows = (int) (dim);
public static void main(String[] args) {
new MemoryMainFrame();
}
public MemoryMainFrame() {
this.setTitle("MemoryGame!!!");
this.setSize(400, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
mainPanel.setBackground(Color.BLACK);
mainPanel.setLayout(new GridBagLayout());
// execution
FillButtonArray(SIXTEEN_BUTTONS);
AddButtonListener(SIXTEEN_BUTTONS);
ButtonToPanel(SIXTEEN_BUTTONS);
this.add(mainPanel);
}
public void FillButtonArray(int numOfButtons) {
int i = 0;
while (i < numOfButtons) {
button[i] = new JButton("asdf");
}
}
public void AddButtonListener(int numOfButtons) {
int i = 0;
while (i < numOfButtons) {
button[i].addActionListener(this);
}
}
public void ButtonToPanel(int numOfButtons) {
int n = 0;
GridBagConstraints gbc = new GridBagConstraints();
for (int i = 0; i < numOfColumns; i++) {
for (int j = 0; j < numOfRows; j++) {
gbc.gridx = i;
gbc.gridy = j;
n++;
button[n].setBorder(BorderFactory.createLineBorder(
Color.DARK_GRAY, 2));
mainPanel.add(button[n]);
}
}
}
public void actionPerformed(ActionEvent arg0) {
JFrame j = new JFrame();
j.setSize(300, 300);
j.setVisible(true);
}
}
我使用“asdf”作为测试,看看按钮是否也能正常工作
此外,执行的操作也是一项测试。这部分代码是不相关的
# 1 楼答案
您正在创建GridBagConstraints,但没有使用它们
更改此项:
为此:
编辑
这里还有一个永无止境的循环:
对于
AddButtonListener(...)
方法也是如此您需要通过使用for循环或在循环中更改
i
来修复此问题同样根据Andrew Thompson的评论,在添加所有组件之前,您将JFrame设置为可见太早了
另外,使用
Math.sqrt
然后将结果强制转换为int是非常危险的,可能会得到意外的结果。如果需要,只需将边长声明为8并将整数平方即可有关GridBagLayout的示例,请查看: