我该如何消除由gridBagLayout引起的间距,使它们紧贴在一起?
这是我简单添加3个按钮的代码。
我看过这个问题,但没有完整的解决方案How to fix gap in GridBagLayout;
我只想把所有的按钮放在JFrame的顶部。
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyProblem {
private JFrame frame = new JFrame();
public static void main(String[] args) {
new MyProblem();
}
public MyProblem() {
frame.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1;
gc.weighty = 1;
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.anchor = GridBagConstraints.NORTH;
for (int i = 0; i < 3; i++) {
JPanel jPanel = new JPanel(new BorderLayout());
jPanel.setSize(80, 80);
jPanel.add(new JButton("Button " + i),BorderLayout.PAGE_START);
frame.add(jPanel, gc);
gc.gridy++;
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
我的按钮长这样:
我希望我的按钮看起来像这样:
JLabel
的信息,以及这个问题获取有关JButton
的信息。 - goncalotomas