I need to make a couple of buttons on the panel in Java Swing and, of course, I would like them to be the same size. While I stupidly instructed gaps, but it turned out some kind of nonsense. Plus, I would like to skip some space on the panel and add more buttons there, but I don’t understand how to do it.

Screen with program: enter image description here

The program code describing the panel on the right:

JPanel eastPanel = new JPanel(); eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); startButton = new JButton("Старт "); startButton.addActionListener(new StartButtonListener()); startButton.setSize(20, 40); stopButton = new JButton("Стоп "); stopButton.addActionListener(new StopButtonListener()); stopButton.setSize(20, 40); JButton clearButton = new JButton("Очистить"); clearButton.addActionListener(new ClearButtonListener()); clearButton.setSize(20, 40); startButton.setSize(clearButton.getSize()); stopButton.setSize(clearButton.getSize()); eastPanel.add(startButton); eastPanel.add(stopButton); eastPanel.add(clearButton); 

Entire project entirely

  • Use a layer manager . Using GridBagLayout, for example, you can make buttons in 2 columns. - Denis

1 answer 1

Discover layers like GridBagLayout and GridLayout. They will help solve many problems.

  GridBagConstraints layConstraints; JPanel eastPanel = new JPanel(); eastPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); // отступ внутри панели на 4 пикселя со всех сторон GridBagLayout layout = new GridBagLayout(); layout.rowHeights = new int[]{23, 23, 23, 0}; // высоты кнопок layout.columnWeights = new double[]{1.0}; layout.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE}; eastPanel.setLayout(layout); startButton = new JButton("Старт"); startButton.addActionListener(new StartButtonListener()); layConstraints = new GridBagConstraints(); layConstraints.fill = GridBagConstraints.BOTH; // заполняет ячейку целиком layConstraints.gridx = 0; // координаты ячейки, в которую помещается кнопка layConstraints.gridy = 0; eastPanel.add(startButton, layConstraints); // добавление кнопки на панель с учётом разметки stopButton = new JButton("Стоп"); stopButton.addActionListener(new StopButtonListener()); layConstraints = new GridBagConstraints(); layConstraints.fill = GridBagConstraints.BOTH; layConstraints.gridx = 0; layConstraints.gridy = 1; eastPanel.add(stopButton, layConstraints); JButton clearButton = new JButton("Очистить"); clearButton.addActionListener(new ClearButtonListener()); layConstraints = new GridBagConstraints(); layConstraints.fill = GridBagConstraints.BOTH; layConstraints.gridx = 0; layConstraints.gridy = 2; eastPanel.add(clearButton, layConstraints);