Java/斯卡拉 Swing : Make a component fill all available space in a row

标签 java swing scala layout-manager gridbaglayout

我正在尝试使用 GridBagLayout 通过 Swing 创建布局。

我想在 Button 旁边放置一个 ComboBox,其中 Button 具有恒定大小,并且 ComboBox 填充行中的所有可用空间:

It Should look like this

但是,如果我放大窗口,ComboBox 和 Button 之间会出现空白区域:

Sadly, it looks more like this

如何布置此表单,以便 ComboBox 填满所有空间,即使在调整窗口大小时也是如此?

组件的布局代码,在 Scala 中:

layout(button) = new Constraints() {
    gridx = 1
    gridy = 0
    anchor = GridBagPanel.Anchor.LineEnd
}

layout(comboBox) = new Constraints() {
    gridx = 0
    gridy = 0
    fill = GridBagPanel.Fill.Horizontal
}

layout(centerPanel) = new Constraints() {
    gridx = 0
    gridy = 1
    weighty = 1
    weightx = 1
    gridwidth = 2
    fill = GridBagPanel.Fill.Both
}

最佳答案

为 GUI 的该部分使用 BorderLayout。放组合。在 CENTERLINE_END 中的按钮。

像这样:

enter image description here

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.*;

public class StretchComboLayout {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel ui = new JPanel(new BorderLayout(2, 2));
                ui.setBorder(new EmptyBorder(4, 4, 4, 4));

                JPanel controls = new JPanel(new BorderLayout(2, 2));
                ui.add(controls, BorderLayout.PAGE_START);
                String s = new String(Character.toChars(8594));
                String[] items = {"Choice: right " + s + " arrow"};
                JComboBox cb = new JComboBox(items);
                controls.add(cb, BorderLayout.CENTER);
                controls.add(new JButton("Button"), BorderLayout.LINE_END);

                JSplitPane sp = new JSplitPane(
                        JSplitPane.VERTICAL_SPLIT, 
                        new JTextArea(4,40), 
                        new JTextArea(4,40));

                ui.add(sp, BorderLayout.CENTER);

                JFrame f = new JFrame("Stretch Combo Layout");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setContentPane(ui);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

关于Java/斯卡拉 Swing : Make a component fill all available space in a row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337074/

相关文章:

java - public void actionPerformed(ActionEvent e) 中表达式的非法开始

bluefish 中的 scala 语法突出显示

java - 插入后获取生成的id

java - 为什么只有少量的Java库里面包含module-info.class?

java - 实体设计JPA

Java - PaintComponent 不会在 JPanel 上显示绘图

java - 想要暂停代码直到用户使用按钮

Scala 无形 : derive type from Mapper

Scala 隐式作用域需要双重导入

java - JFrame 背景颜色闪烁但随后恢复