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

  发布于 2023-01-31 18:56

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

Eclipse的Formatter首选项

目前我已通过以下方式尝试此操作:

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();
    }
}

结果如下:

结果没有间距

我的代码有几个问题.首先,我不明白为什么我必须让插图消极.根据Oracle的教程 "默认情况下,每个组件都没有外部填充." 因此,默认情况下不应该没有空格吗?没有负面插图,结果如下所示:

结果没有设置负插入

其次,我希望切换按钮变暗而不是转为蓝色并切换为"打开".有没有简单的方法通过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();
}

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

使用BoxLayout

我希望尽可能保持按钮的一般外观,但是边缘应该更加矩形,以便切换按钮看起来更加连接.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有