0

I have this code below to create a page inside of a tab. I want each layout in one row of the overall box layout but i want the elements to stay in their original size and not expand to fill the width of the overall window. does anyone know what lines of code i need to change or what is the best way of doing this?! The image attached shows what it looks like at the moment

enter image description here

public void createPage4() {
    panel4 = new JPanel();
    panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
    navigatePanel = new JPanel();
    navigatePanel.setLayout(new BoxLayout(navigatePanel, BoxLayout.X_AXIS));
    previousButton.setText("Previous");
    previousButton.setEnabled(false);
    navigatePanel.add(previousButton);
    navigatePanel.add(Box.createHorizontalStrut(10));
    indexTextField.setHorizontalAlignment(JTextField.CENTER);
    navigatePanel.add(indexTextField);
    navigatePanel.add(Box.createHorizontalStrut(10));
    ofLabel.setText("of");
    navigatePanel.add(ofLabel);
    navigatePanel.add(Box.createHorizontalStrut(10));
    maxTextField.setHorizontalAlignment(JTextField.CENTER);
    maxTextField.setEditable(false);
    navigatePanel.add(maxTextField);
    navigatePanel.add(Box.createHorizontalStrut(10));
    nextButton.setText("Next");
    nextButton.setEnabled(false);
    navigatePanel.add(nextButton);
    panel4.add(navigatePanel);
    displayPanel = new JPanel();
    displayPanel.setLayout(new GridLayout(5, 2, 4, 4));
    firstNameLabel.setText("First Name:");
    displayPanel.add(firstNameLabel);
    displayPanel.add(firstNameTextField);
    lastNameLabel.setText("Last Name:");
    displayPanel.add(lastNameLabel);
    displayPanel.add(lastNameTextField);
    panel4.add(displayPanel);
}

image

image

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Kevin Foley
  • 119
  • 1
  • 8

2 Answers2

2
  • BoxLayout accepting Min, Max and PreferredSize that came from JComponents

I want each layout in one row of the overall box layout but i want the elements to stay in their original size and not expand to fill the width of the overall window

mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

The easiest way is to add your panel4 to an other panel that uses GridBagLayout and then add that panel to the container. Then it will be centered and nothing will stretch on resize.

JPanel centeredPanel = new JPanel(new GridBagLayout());
centeredPanel.add(panel4);    // add this panel to the container

You should also construct the textfields with a specified number of columns, like

indexTextField = new JTextField(20);
Rempelos
  • 1,220
  • 10
  • 18