java - 有没有办法在 GridBagLayout 的开头放置具有不同空格的 JButton?
问题描述
我正在尝试做这样的事情:
但我不能在按钮前留下空格。我试图添加隐形按钮,但没有任何改变。
for (int i = 0; i < gameSize; i++ ){
c.gridwidth = (i+1)*2;
c.gridx = 0;
c.gridy = 4*i;
JRadioButton temp = new JRadioButton();
temp.setVisible(false);
board.add(temp,c);
for(int j = 0; j < gameSize; j++){
c.gridwidth = 4;
c.gridx = 2+(4*j);
c.gridy = 2+(4*i);
cells[i][j] = new JButton();
cells[i][j].setBackground(Color.white);
board.add(cells[i][j],c);
}
}
它看起来像[这个:
当我让它们可见时。我不明白为什么它们的宽度仍然是 4,即使我将它分配给 (i+1)*2。
我是 Java 新手,对 Java GUI 非常陌生。所以,也许我没有弄清楚最基本的事情。感谢您的建议!
解决方案
我创建了以下 GUI。
为了做到这一点,我不得不使用 Swing 布局的组合。
每行上的按钮都是用 aJPanel
和 a创建的GridLayout
。该行是使用带有 的行创建JPanel
的FlowLayout
,使用 dummyJLabel
和按钮 row JPanel
。
主要JPanel
使用GridLayout
(0, 1) 的 a 来创建交错效果。每行中的虚拟JLabel
对象变大了JButtons
.
这是完整的可运行代码。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GridBagLayoutStaggeredGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new GridBagLayoutStaggeredGUI());
}
@Override
public void run() {
JFrame frame = new JFrame("Staggered Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
int gameSize = 8;
int buttonSize = 50;
int inset = 2;
JButton[][] cells = new JButton[gameSize][gameSize];
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (int i = 0; i < gameSize; i++) {
JPanel innerPanel = new JPanel(
new FlowLayout(FlowLayout.LEADING, 0, 0));
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(inset, buttonSize));
innerPanel.add(label);
innerPanel.add(createRowPanel(cells[i], buttonSize));
panel.add(innerPanel);
inset += buttonSize / 2;
}
return panel;
}
private JPanel createRowPanel(JButton[] cells, int buttonSize) {
JPanel panel = new JPanel(new GridLayout(0, cells.length, 0, 0));
for (int i = 0; i < cells.length; i++) {
cells[i] = new JButton();
cells[i].setBackground(Color.white);
cells[i].setPreferredSize(new Dimension(buttonSize, buttonSize));
panel.add(cells[i]);
}
return panel;
}
}
推荐阅读
- php - 来自 JOOMLA 的错误 403
- android - 用于 Android 和 iOS 应用程序测试自动化的工具?
- javascript - Javascript,一个带有回调处理程序的对象,如何将其重写为等待/异步样式?
- ios - 具有不同 UITableViewCells 和动态内容的 UITableView
- angular - Angular 6更改单选按钮更改标签类
- elasticsearch - 在 Elasticsearch 中使用 ngram 时如何控制结果的评分或排序?
- c++ - C++ 11 中具有多个模板参数的模板函数的特化
- c++ - Using a shared library in another shared library
- javascript - 激活弹出窗口(HTML、PHP、Javascript/Jquery)
- html - 向锚添加底部边距是否有任何“陷阱”?