java swing borderlayout constraints error

32 Views Asked by At

I am new to Java Swing and I have been trying to create a vertical menu panel but I having been facing trouble in adding it to the left middle of the frame. I have a little knowledge on the layout packages provided by Swing and tried many ways to resolve this issue yet failed to fix it.

Here's the code I tried:

this.mainPanel = new JPanel();

// Set up the button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));

// Set a border for the button panel using a TitledBorder
TitledBorder border = BorderFactory.createTitledBorder("Menu");
buttonPanel.setBorder(border);

// Create three buttons with different text
this.homeMenuButton = new JButton("Home");
this.DoctorMenuButton = new JButton("Doctors");
this.ConsultationsMenuButton = new JButton("Consultations");
this.notesMenuButton = new JButton("Notes");
this.viewConsultationsMenuButton = new JButton("View Consultations");

buttonPanel.add(homeMenuButton);
buttonPanel.add(DoctorMenuButton);
buttonPanel.add(ConsultationsMenuButton);
buttonPanel.add(notesMenuButton);
buttonPanel.add(viewConsultationsMenuButton);

GroupLayout layout = new GroupLayout(buttonPanel);
buttonPanel.setLayout(layout);

layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

layout.setHorizontalGroup(
        layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(homeMenuButton)
                .addComponent(DoctorMenuButton)
                .addComponent(ConsultationsMenuButton)
                .addComponent(notesMenuButton)
                .addComponent(viewConsultationsMenuButton)
);

layout.setVerticalGroup(
        layout.createSequentialGroup()
                .addComponent(homeMenuButton)
                .addComponent(DoctorMenuButton)
                .addComponent(ConsultationsMenuButton)
                .addComponent(notesMenuButton)
                .addComponent(viewConsultationsMenuButton)
);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(buttonPanel, gbc);

I tried adding BorderLayout "west" constraint and failed.

0

There are 0 best solutions below