非常简单的问题:如何消除包含两个JCheckBox
的两个单元格之间的垂直间隙?我用红色边框标记了图片中的间隙。
以下是代码:
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class Main {
public static void main(String[] args) {
JPanel somePanel = new JPanel();
somePanel.setLayout(new MigLayout("insets 0, debug", "", ""));
somePanel.add(new JCheckBox("first option"), "h 20!");
somePanel.add(new JButton("click me"), "spany 2, h 40!, w 60%, wrap");
somePanel.add(new JCheckBox("option two"), "h 20!");
JFrame frame = new JFrame();
frame.setContentPane(somePanel);
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:3)
如果只应在特定行/列之间应用最小间隙,则在行/列约束中定义最小间隙:
new MigLayout("insets 0, debug", "", "[]0[]"));
(想知道这对你不起作用?这里很好:)。
或在layoutContraints中,如果它们应该应用于所有行:
new MigLayout("insets 0, gapy 0, debug"));
BTW:布局“编码”应遵循与所有编码相同的规则,f.i。干:-)特别是,我的规则是不重复组件约束,如果你可以实现布局/行约束的目标。在示例中,除了跨越:之外,您可以除去所有组件约束
somePanel.setLayout(new MigLayout("insets 0, debug, wrap 2",
"[][60%, fill]", "[20!, fill]0"));
somePanel.add(new JCheckBox("first option"));
somePanel.add(new JButton("click me"), "spany 2");
somePanel.add(new JCheckBox("option two"));
答案 1 :(得分:2)
好的,我刚刚找到了一个使用对接的好解决方案:
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class Main {
public static void main(String[] args) {
JPanel somePanel = new JPanel();
somePanel.setLayout(new MigLayout("insets 0, debug", "", ""));
somePanel.add(new JButton("click me"), "east");
somePanel.add(new JCheckBox("first option"), "north");
somePanel.add(new JCheckBox("option two"), "south");
JFrame frame = new JFrame();
frame.setContentPane(somePanel);
frame.pack();
frame.setVisible(true);
}
}
但是,如果停靠不是一个选项,我该怎么办呢?
答案 2 :(得分:0)
另一个解决方案是将单元格拆分为两个子单元,将复选框放在那里,然后应用组件间隙约束。
package com.zetcode;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
Demonstrating component gaps in MigLayout manager.
Author: Jan Bodnar
Website: zetcode.com
*/
public class MigLayoutGapsEx extends JFrame {
public MigLayoutGapsEx() {
initUI();
}
private void initUI() {
JCheckBox cb1 = new JCheckBox("First option");
JCheckBox cb2 = new JCheckBox("Second option");
JButton btn = new JButton("Click me");
createLayout(cb1, cb2, btn);
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout());
add(arg[0], "split 2, flowy");
add(arg[1], "gapy 0");
add(arg[2]);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutGapsEx ex = new MigLayoutGapsEx();
ex.setVisible(true);
});
}
}
以下是截图: