Syntax error How to align multiple buttons with different height in Java?

How to align multiple buttons with different height in Java?



To align multiple buttons with different height in Java, try the following example, Here, we have set 5 buttons with GridBagConstraints −

GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 5, 5);
constraints.anchor = GridBagConstraints.WEST;

In addition, to set different height for different buttons, we have used −

component. getPreferredSize().height

The following is an example to align multiple buttons with different height −

Example

package my;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      final JFrame frame = new JFrame(SwingDemo.class.getSimpleName());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel panel = new JPanel(new GridBagLayout());
      GridBagConstraints constraints = new GridBagConstraints();
      constraints.insets = new Insets(5, 5, 5, 5);
      constraints.anchor = GridBagConstraints.WEST;
      JButton btn1 = new JButton("1");
      panel.add(btn1, constraints);
      JButton btn2 = new JButton("2");
      btn2.setPreferredSize(new Dimension(btn1.getPreferredSize().width, btn1 .getPreferredSize().height + 30));
      panel.add(btn2, constraints);
      JButton btn3 = new JButton("3");
      btn3.setPreferredSize(new Dimension(btn2.getPreferredSize().width, btn2 .getPreferredSize().height + 20));
      panel.add(btn3, constraints);
      JButton btn4 = new JButton("4");
      btn4.setPreferredSize(new Dimension(btn2.getPreferredSize().width, btn3 .getPreferredSize().height + 5));
      panel.add(btn4, constraints);
      JButton btn5 = new JButton("5");
      btn5.setPreferredSize(new Dimension(btn2.getPreferredSize().width, btn3 .getPreferredSize().height + 50));
      panel.add(btn5, constraints);
      frame.add(panel);
      frame.pack();
      frame.setVisible(true);
   }
}

Output


Updated on: 2019-07-30T22:30:26+05:30

569 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements