我想创建一个按钮网格。按钮之间不应有空格,以便按钮接触下一个按钮。
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class Bild extends JFrame {
public static class createButton extends JPanel {
public createButton() {
JButton b = new JButton();
Border border = new LineBorder(Color.BLACK, 1);
b.setBorder(border);
b.setBackground(Color.WHITE);
b.setPreferredSize (new Dimension(10,10));
this.add(b);
}
}
public Bild() {
GridLayout layout = new GridLayout(10,10,0,0);
this.setLayout(layout);
for (int i = 0; i < 100; i++) {
this.add(new createButton());
}
}
}
import javax.swing.*;
import java.awt.*;
public class Main{
public static void main (String[] args) {
JFrame frame = new Bild();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
使用网格布局,我尝试获得 10x10 的按钮网格。但是,尽管我使用参数 10,10,0,0 创建了 GridLayout,但按钮之间有一个空格。 我的错误在哪里?
最佳答案
这是因为createButton
实际上是一个JPanel
,它有一个FlowLayout
因为它是默认的布局管理器。让 createButton
成为一个返回 JButton
的方法,该按钮将跨越单元格内的整个空间。 (您可以删除setPreferredSize()
)。如果您希望按钮保持 10x10 像素并在框架内居中:将主面板的布局管理器设置为 GridBagLayout 并添加一个带有 的
到它。也许还可以重写按钮的 JPanel
GridLayoutgetPreferredSize()
而不是调用 setPreferredSize()
。
跨越整个屏幕的按钮:
class Bild extends JFrame {
public JButton createButton() {
JButton b = new JButton();
Border border = new LineBorder(Color.BLACK, 1);
b.setBorder(border);
b.setBackground(Color.WHITE);
return b;
}
public Bild() {
setLayout(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
add(createButton());
}
}
}
剩余按钮 10x10:
class Bild extends JFrame {
public JButton createButton() {
JButton b = new JButton() {
@Override
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
};
Border border = new LineBorder(Color.BLACK, 1);
b.setBorder(border);
b.setBackground(Color.WHITE);
return b;
}
public Bild() {
JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
panel.add(createButton());
}
setLayout(new GridBagLayout());
add(panel);
}
}
关于Java GUI Swing,GridLayout 中的按钮,按钮之间没有空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330955/