简体   繁体   中英

GUI Layout with swing components JAVA

This is what i want to achieve 在此处输入图片说明

I used grid layout and this is what have 请忽略文本字段中显示的文本

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.

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

在此处输入图片说明

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...

在此处输入图片说明

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...

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM