GridBagLayout Добавление пробела между кнопками/ступенчатыми/разнообразными столбцами?

Я пытаюсь создать макет с помощью GridBagLayout, но у меня возникают проблемы с тем, чтобы промежутки между элементами управления JButton были равными. В первом ряду есть 5 кнопок, между которыми нет места. Во втором и третьем ряду должно быть по 4 кнопки меньшего размера между ними.

Обходной путь, который я пробовал, состоял в том, чтобы сделать его сеткой 35x35, где верхние кнопки имеют ширину 7, а другие кнопки - ширину 5. Я не могу понять, как заставить 4 кнопки выровняться равномерно (пространство в последнем столбце меньше).

GridBagLayout Добавление пробела между кнопками/ступенчатыми/разнообразными столбцами?

Код ниже:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import java.awt.Insets;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

public class MainTwo {
    public static void main(String[] a) {
        final JColorChooser colorChooser = new JColorChooser();
        MyChooserPanel newChooser = new MyChooserPanel();
        colorChooser.addChooserPanel(newChooser);

        ActionListener okActionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println(colorChooser.getColor());
            }
        };

        ActionListener cancelActionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Cancel");
            }
        };

        final JDialog dialog = JColorChooser.createDialog(null, "Change Button Background", true, colorChooser,
                okActionListener, cancelActionListener);
        dialog.setVisible(true);
    }
}

class MyChooserPanel extends AbstractColorChooserPanel {
    public void buildChooser() {
        setLayout(new GridBagLayout()); 
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.NONE;
        c.ipadx = 21;
        c.ipady = 15;
        c.gridwidth = 7;
        makeAddButton("Black", Color.BLACK, c);
        makeAddButton("Dark Grey", Color.PINK, c);
        makeAddButton("Custom PathVisio Grey", Color.YELLOW, c);
        makeAddButton("Grey", Color.CYAN, c);
        makeAddButton("White", Color.WHITE, c);
        c.ipadx = 15;
        c.gridwidth = 5;
        c.insets = new Insets(10,0,0,0);
        c.gridy = 1; // new row
        makeAddButton("Blue", Color.BLUE, c);
        c.gridx = 10;
        makeAddButton("Green", Color.GREEN, c);
        c.gridx = 20;
        makeAddButton("Purple", Color.MAGENTA, c);
        c.gridx = 30;
        makeAddButton("Orange", Color.ORANGE, c);
        c.gridy = 2; // new row
        c.gridx = 0;
        makeAddButton("Dark Blue", Color.BLUE, c);
        c.gridx = 10;
        makeAddButton("Dark Green", Color.GREEN, c);
        c.gridx = 20;
        makeAddButton("Dark Purple", Color.MAGENTA, c);
        c.gridx = 30;
        makeAddButton("Dark Orange", Color.ORANGE, c);
    }

    public void updateChooser() {
    }

    public String getDisplayName() {
        return "Panel";
    }

    public Icon getSmallDisplayIcon() {
        return null;
    }

    public Icon getLargeDisplayIcon() {
        return null;
    }

    private void makeAddButton(String name, Color color, GridBagConstraints c) {
        JButton button = new JButton(name);
        button.setBackground(color);
        button.setBorderPainted(false);
        button.setOpaque(true);
        button.setAction(setColorAction);
        button.setToolTipText(name);
        add(button, c);
    }

    Action setColorAction = new AbstractAction() {
        public void actionPerformed(ActionEvent evt) {
            JButton button = (JButton) evt.getSource();
            getColorSelectionModel().setSelectedColor(button.getBackground());
        }
    };
}
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
1
0
38
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Обычно я против использования нескольких макетов для достижения цели, но в этом случае я предлагаю разделить его на 2 панели. Вот пример:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridBagLayout());
    Insets insets = new Insets(4, 4, 4, 4);
    
    JPanel top = new JPanel(new GridBagLayout());
    top.add(new JButton("Top 1"), new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    top.add(new JButton("Top 2"), new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    top.add(new JButton("Top 3"), new GridBagConstraints(2, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    top.add(new JButton("Top 4"), new GridBagConstraints(3, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    top.add(new JButton("Top 5"), new GridBagConstraints(4, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    
    JPanel bottom = new JPanel(new GridBagLayout());
    bottom.add(new JButton("Mid 1"), new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    bottom.add(new JButton("Mid 2"), new GridBagConstraints(1, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    bottom.add(new JButton("Mid 3"), new GridBagConstraints(2, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    bottom.add(new JButton("Mid 4"), new GridBagConstraints(3, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    
    bottom.add(new JButton("Bot 1"), new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    bottom.add(new JButton("Bot 2"), new GridBagConstraints(1, 2, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    bottom.add(new JButton("Bot 3"), new GridBagConstraints(2, 2, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    bottom.add(new JButton("Bot 4"), new GridBagConstraints(3, 2, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    
    frame.add(top, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    frame.add(bottom, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
Ответ принят как подходящий

Я бы подошел к этому графическому интерфейсу как к одному макету границы, содержащему два макета сетки.

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

public class FiveAndEightLayout {

    public FiveAndEightLayout() {
        JPanel gui = new JPanel(new BorderLayout(4,4));
        gui.setBorder(new TitledBorder("Border Layout"));

        JPanel topPanel = new JPanel(new GridLayout(1,0,0,0));
        for (int ii=1; ii<6; ii++) {
            topPanel.add(new JButton("Button " + ii));
        }
        topPanel.setBorder(new TitledBorder("Grid Layout"));
        gui.add(topPanel, BorderLayout.PAGE_START);

        JPanel centerPanel = new JPanel(new GridLayout(0,4,15,5));
        for (int ii=1; ii<9; ii++) {
            centerPanel.add(new JButton("Button " + ii));
        }
        centerPanel.setBorder(new TitledBorder("Grid Layout"));
        gui.add(centerPanel, BorderLayout.CENTER);

        JFrame f = new JFrame("Five And Eight Layout");
        f.add(gui);
        f.pack();
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                new FiveAndEightLayout();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

Другие вопросы по теме