0

This is what i want to achieve enter image description here

I used grid layout and this is what have Please ignore the text displayed in textfield

and my code goes (not full code can provide one if needed).

       components.setLayout(new GridLayout(4,0));

       components.setBorder(BorderFactory.createTitledBorder("Personal Data"));

       //Lable to display
       name.setText("Resident Name");
       roomNo.setText("Room Number");
       age.setText("Age");
       gender.setText("Gender");
       careLvl.setText("Care Level");


       components.add(name);
       components.add(textFieldForName);
       components.add(roomNo);
       components.add(textFieldForAge);

       components.add(age);
       components.add(coForAge);
       components.add(gender);
       components.add(coForGender);
       components.add(careLvl);
       components.add(coForCareLvl);

any heads up would be greatly appreciated.

4
  • For designing static GUI elements, most especially forms, you would find it much easier to develop your user interface visually with a form designer. If this option is available to you, I would use Scene Builder 1.1 to create the FXML file which could then be loaded into Java FX 2.2 to generate the scene object graph for your GUI form. Using Scene Builder greatly accelerates the development of forms and takes almost all of the GUI creational code out of your application and moves it into an XML file that is far more easily maintained. Commented Sep 5, 2013 at 0:16
  • 1
    @scottb 1- What part of the question makes you think it's about Java FX? 2- IMHO, one should learn to hand code a UI before relying on a tool. It provides greater understanding of how the layout managers work and can work with each other. Yes I use a form editor on a daily bases, I also spend a lot of time creating UI's by hand as well. Commented Sep 5, 2013 at 2:25
  • @MadProgrammer: Save the rage and read down to the part where it says "if this option is available to you." Most problems have more than one solution and suggesting alternative approaches is a valid use of SO ... even if the alternative presents an affront to your personal world view of how things ought to be done. Commented Sep 5, 2013 at 4:24
  • @scottb Sorry if offended, I was curious as to why you would suggest JavaFX when the question was Swing based, consideration that both Eclipse and NetBeans also offer Swing based form designers. Commented Sep 5, 2013 at 4:31

2 Answers 2

1

GridLayout does just that, it layouts components out in a grid, where each cell is percentage of the available space based on the requirements (ie width / columns and height / rows).

Take a look at A Visual Guide to Layout Managers for examples of the basic layout managers and what they do.

I would recommend that you take a look at GridBagLayout instead. It is the most flexible (and most complex) layout manager available in the default libraries.

For Example

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestLayout31 {

    public static void main(String[] args) {
        new TestLayout31();
    }

    public TestLayout31() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {

            JLabel lblRes = new JLabel("Resident Name");
            JLabel lblRoomNo = new JLabel("RoomNo");
            JLabel lblAge = new JLabel("Age");
            JLabel lblGender = new JLabel("Gender");
            JLabel lblCare = new JLabel("Care level");

            JTextField fldRes = new JTextField("john smith", 20);
            JTextField fldRoomNo = new JTextField(10);
            JComboBox cmbAge = new JComboBox(new Object[]{51});
            JComboBox cmbGener = new JComboBox(new Object[]{"M", "F"});
            JComboBox cmbCare = new JComboBox(new Object[]{"Low"});

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets = new Insets(1, 1, 1, 1);
            add(lblRes, gbc);

            gbc.gridx++;
            gbc.gridwidth = 4;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(fldRes, gbc);

            gbc.gridx = 7;
            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.NONE;
            add(lblRoomNo, gbc);

            gbc.gridx++;
            add(fldRoomNo, gbc);

            gbc.gridy++;
            gbc.gridx = 1;
            add(lblAge, gbc);
            gbc.gridx++;
            add(cmbAge, gbc);
            gbc.gridx++;
            add(lblGender, gbc);
            gbc.gridx++;
            add(cmbGener, gbc);
            gbc.gridx++;
            gbc.gridwidth = 2;
            add(lblCare, gbc);
            gbc.gridx += 2;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(cmbCare, gbc);

        }
    }

}

Compound Layout Example

Another option would be to use a compound layout. This is, you separate each section of your UI into separate containers, concentrating on their individual layout requirements.

For example, you have two rows of fields, each which don't really relate to each other, so rather than trying to figure out how to make the fields line up, you can focus on each row separately...

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestLayout31 {

    public static void main(String[] args) {
        new TestLayout31();
    }

    public TestLayout31() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {

            JPanel topPane = new JPanel(new GridBagLayout());

            JLabel lblRes = new JLabel("Resident Name");
            JLabel lblRoomNo = new JLabel("RoomNo");
            JLabel lblAge = new JLabel("Age");
            JLabel lblGender = new JLabel("Gender");
            JLabel lblCare = new JLabel("Care level");

            JTextField fldRes = new JTextField("john smith", 20);
            JTextField fldRoomNo = new JTextField(10);
            JComboBox cmbAge = new JComboBox(new Object[]{51});
            JComboBox cmbGener = new JComboBox(new Object[]{"M", "F"});
            JComboBox cmbCare = new JComboBox(new Object[]{"Low"});

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets = new Insets(1, 1, 1, 1);
            topPane.add(lblRes, gbc);

            gbc.gridx++;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            topPane.add(fldRes, gbc);

            gbc.gridx++;
            topPane.add(lblRoomNo, gbc);

            gbc.gridx++;
            topPane.add(fldRoomNo, gbc);

            JPanel bottomPane = new JPanel(new GridBagLayout());

            gbc.gridx = 0;
            bottomPane.add(lblAge, gbc);
            gbc.gridx++;
            bottomPane.add(cmbAge, gbc);
            gbc.gridx++;
            bottomPane.add(lblGender, gbc);
            gbc.gridx++;
            bottomPane.add(cmbGener, gbc);
            gbc.gridx++;
            bottomPane.add(lblCare, gbc);
            gbc.gridx++;
            bottomPane.add(cmbCare, gbc);

            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(topPane, gbc);
            gbc.gridy++;
            add(bottomPane, gbc);

        }
    }        
}

This will make it easier to modify the UI later should you have to...

Sign up to request clarification or add additional context in comments.

1 Comment

Each layout has specific traits, while I tend to use GridBagLayout a lot, don't discount the others, which may produce the same desired result with less code. For example, in the second example, I could have used GridLayout configured with a single column and two rows to layout the top and bottom panels...
1
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
JPanel northPane   = new JPanel();
JPanel centerPane  = new JPanel();
JPanel southPane   = new JPanel();
contentPane.setLayout(new BorderLayout());
northPane.setLayout(  new GridLayout(1, 6));
southPane.setLayout(  new GridLayout(1, 7));
contentPane.add(northPane,  BorderLayout.NORTH );
contentPane.add(centerPane, BorderLayout.CENTER);
contentPane.add(southPane,  BorderLayout.SOUTH );
frame.setContentPane(contentPane);
JLabel            residentNameLabel = new JLabel("Resident name ");
JTextField        residentNameText  = new JTextField();
JLabel            roomNoLabel       = new JLabel("RoomNo ");
JTextField        roomNoText        = new JTextField();
JLabel            emptyLabel0       = new JLabel("   ");
JLabel            emptyLabel1       = new JLabel("   ");
JLabel            emptyLabel2       = new JLabel("   ");
JLabel            emptyLabel3       = new JLabel("   ");
JLabel            ageLabel          = new JLabel("Age ");
JComboBox<String> ageComboBox       = new JComboBox<String>();
ageComboBox.addItem("50");
ageComboBox.addItem("51");
ageComboBox.addItem("52");
ageComboBox.addItem("53");
ageComboBox.addItem("54");
ageComboBox.addItem("55");
JLabel            genderLabel       = new JLabel("Gender ");
JComboBox<String> genderComboBox    = new JComboBox<String>();
genderComboBox.addItem("M");
genderComboBox.addItem("F");
JLabel            careLevelLabel    = new JLabel("Care Level ");
JComboBox<String> careLevelComboBox = new JComboBox<String>();
genderComboBox.addItem("low");;
genderComboBox.addItem("medium");
genderComboBox.addItem("high");
residentNameLabel.setHorizontalAlignment(JLabel.RIGHT);
roomNoLabel.setHorizontalAlignment(JLabel.RIGHT);
ageLabel.setHorizontalAlignment(JLabel.RIGHT);
genderLabel.setHorizontalAlignment(JLabel.RIGHT);
careLevelLabel.setHorizontalAlignment(JLabel.RIGHT);
northPane.add(emptyLabel0      );
northPane.add(residentNameLabel);
northPane.add(residentNameText );
northPane.add(roomNoLabel      );
northPane.add(roomNoText       );
northPane.add(emptyLabel1      );
centerPane.add(emptyLabel2     );
southPane.add(ageLabel         );
southPane.add(ageComboBox      );
southPane.add(genderLabel      );
southPane.add(genderComboBox   );
southPane.add(careLevelLabel   );
southPane.add(careLevelComboBox);
southPane.add(emptyLabel3      );
contentPane.setBorder(BorderFactory.createTitledBorder("Personal Data"));
frame.addWindowListener(new WindowAdapter() {
@Override
    public void windowClosing(WindowEvent evt) {
        System.exit(0);
    }
});
frame.setVisible(true);
frame.pack();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.