java - 如何在 Java 中创建带有连接按钮的 ButtonGroup?

标签 java swing layout gridbaglayout jtogglebutton

我目前正在尝试创建一组类似于 Eclipse 格式化程序首选项中使用的切换按钮:

Formatter preferences of Eclipse

目前我尝试过以下方式:

public class Exercise extends JFrame {

    private String[] buttonNames = {"A", "B", "C", "D", "E"};

    Exercise() {
        final JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        int tabCount = 0;
        final ButtonGroup topButtonGroup = new ButtonGroup();
        for (String buttonName : buttonNames) {
            JToggleButton tabButton = new JToggleButton(buttonName);
            topButtonGroup.add(tabButton);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.insets = new Insets(0, -6, 0, -7); // Questionable line
            c.gridx = tabCount;
            c.gridy = 0;
            topPanel.add(tabButton, c);
            tabCount++;
        }
        this.add(topPanel);
        this.setVisible(true);
        this.pack();
    }

    public static void main(String[] args) {
        new Exercise();
    }
}

结果如下:

Result without spacing

我的代码有几个问题。首先,我不明白为什么我必须使插图为负数。根据Oracle's tutorial , “[b] 默认情况下,每个组件都没有外部填充。”因此,默认情况下不应该没有空格吗?没有负插图,结果如下所示:

Result without setting negative insets

其次,我想让切换按钮变暗而不是在切换为“打开”时变成蓝色。有什么简单的方法可以通过 Java Swing 做到这一点?最后,总体上有没有更好的方法?我很想知道 Eclipse 是如何设法让切换按钮看起来像是完美连接的。

更新

我已尝试按照推荐使用 BoxLayout。不幸的是,这似乎并没有解决问题。结果与上图几乎相同。这是修改后的构造函数:

Exercise() {
    final JPanel topPanel = new JPanel();
    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
    final ButtonGroup topButtonGroup = new ButtonGroup();
    for (String buttonName : buttonNames) {
        JToggleButton tabButton = new JToggleButton(buttonName);
    //    tabButton.setBorder(BorderFactory.createBevelBorder(
    //              BevelBorder.RAISED, Color.LIGHT_GRAY, Color.DARK_GRAY));
        topButtonGroup.add(tabButton);
        topPanel.add(tabButton);
    }
    this.add(topPanel);
    this.setVisible(true);
    this.pack();
}

有趣的是,当我按照上面的注释尝试添加边框时,按钮之间的额外间距不知何故消失了。结果如下:

With BoxLayout

我希望尽可能保持按钮的整体外观和以前一样,但边缘更矩形,以便切换按钮看起来更连贯。

最佳答案

您可以使用像 BoxLayout 这样的布局来消除空间。 GridBagLayout 并不是唯一的布局。推荐阅读:http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

您还可以调用 JButton 函数,如 setBorder() 和 setBackground() 来实现您提到的效果。一如既往,API 是您最好的 friend :http://docs.oracle.com/javase/7/docs/api/

关于java - 如何在 Java 中创建带有连接按钮的 ButtonGroup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21310260/

相关文章:

html - 具有百分比宽度的 float div

java - LibGdx font.setColor(Color.WHITE) 不起作用

java - 如何循环在循环期间发生变化的 ArrayList

java - 在 miglayou 中调整表格大小

swing - scala.swing.ListView : single/multiple selection

java - JMeter 与 Java Swing 应用程序

java - 简单的java为什么变量不改变?

java - Java中的优先级信号量

html - CSS 3 列 float (2 个固定,1 个动态)

css - 无法获取页面最右侧的内容