java - 如何正确获得此 GUI 布局?

标签 java swing

我想要这个:

sketch

我试过这个:

    // Vertically center
    formatbp.setLayout (new GridBagLayout()); // formatbp is a JPanel
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;

    rbpanel.setLayout(new BoxLayout(rbpanel, BoxLayout.PAGE_AXIS)); // rbpanel is also a JPanel
    rb = new ButtonGroup();
    rbpanel.add(new JLabel("Words are seperated by: "));

    rbLinesOrTabs.setSelected(true);
    rb.add(rbLinesOrTabs);
    rbpanel.add(rbLinesOrTabs);
    rbLinesOrTabs.addActionListener(this);

    rbotherpanel = new JPanel(new FlowLayout());
    rb.add(rbOther);
    rbpanel.add(rbOther);
    rbOther.addActionListener(this);

    othercharfield.setEnabled(false); // Is going to be enabled when rbOther gets selected (and disabled again when rbLinesOrTabs is selected again), that is where the actionlisteners are for
    rbotherpanel.add(othercharfield);

    rbpanel.add(rbotherpanel);

    formatbp.add(rbpanel,gbc);
    formatbp.add(formatb,gbc); // formatb is the button

(大多数对象在代码的前面初始化)

但这是结果:

result1

我做错了什么?

编辑:我发现我在这里犯了一个错误:

rbpanel.add(rbOther);

那应该是:

rbotherpanel.add(rbOther);

现在我得到:

result2

更好,但其他项目未正确对齐。 (如您所见,它有点向右)

最佳答案

使用 MigLayout 的一体式方法(是的,这确实是我目前最喜欢的 :-)

    MigLayout layout = new MigLayout("debug", "[][]");
    JComponent content = new JPanel(layout);
    content.add(new JLabel("Words are separated by: "), "span");
    JRadioButton radio = new JRadioButton("Lines or tabs");
    content.add(radio, "wrap");
    // split the cell so it will contain both the other button
    // and the textfield
    content.add(new JRadioButton("Other:"), "split 2");
    // get the right margin of the upper radiobutton
    int rightMargin = radio.getInsets().right; 
    content.add(new JTextField(), "grow, wrap, " +
        // remove the gap to the preceding radiobutton
            "gapx 0, " +
        // set the padding to compensate the right edge
            "pad 0 0 0 -" + rightMargin + "px");
    content.add(new JButton("Format"), "span, center");
    showInFrame(content, "align to button text");

共享单元格中微调的视觉效果有点依赖于 LAF。在 Windows 中看起来不错,在 Nimbus 中不太好(后者在没有任何补偿的情况下看起来最好),因此您需要进行一些试验。

关于java - 如何正确获得此 GUI 布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17345124/

相关文章:

java - 在另一个线程中使用在一个线程中生成的数据

java - JTree中如何扩展到特定的TreeNode

java - 将内部类对象作为函数参数传递

java - 通过 SSL 传输安全和消息身份验证之间有什么区别?

java - 为什么我的图像无法保存

java - 获取 Applet 的屏幕截图?

java - 将扩展 JTable 添加到 JFrame

java - 这些 setDefaultCloseOperation 语句之间的区别

java - 如果全部为空,则从 txt 中删除一行

java - Spring-Boot:尝试从 @PostConstruct 方法抛出自定义 RunTimeException 失败