PDA

Click to See Complete Forum and Search --> : Aligning Components


DCorb
Mar 2nd, 2007, 01:50 PM
I have 4 labels all with corresponding textfields to the right of each label.
I also have 1 label with a textarea next to it.
How can I align the labels? I would still like them all in the center of the form but I want the start of each label to be aligned and the start of each textbox to be aligned.

Here is the code for the gui I currently have:



public guithing()
{

c = getContentPane();
c.setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

txtName = new JTextField(10);
txtStudentNo = new JTextField(10);
txtCourse = new JTextField(10);
txtRoomNo = new JTextField(4);
paymentsMade = new JTextArea(3, 28);
output = new JTextArea(8, 30);

JPanel namePanel = new JPanel();
JLabel lblName = new JLabel("Name:");
namePanel.add(lblName);
namePanel.add(txtName);
getContentPane().add(namePanel);

JPanel StudentNoPanel = new JPanel();
JLabel lblStudentNo = new JLabel("Student Number:");
StudentNoPanel.add(lblStudentNo);
StudentNoPanel.add(txtStudentNo);
getContentPane().add(StudentNoPanel);

JPanel coursePanel = new JPanel();
JLabel lblCourse = new JLabel("Course: ");
coursePanel.add(lblCourse);
coursePanel.add(txtCourse);
getContentPane().add(coursePanel);

JPanel RoomNoPanel = new JPanel();
JLabel lblRoomNo = new JLabel("Room Number:");
RoomNoPanel.add(lblRoomNo);
RoomNoPanel.add(txtRoomNo);
getContentPane().add(RoomNoPanel);

JPanel paymentsPanel = new JPanel();
JLabel lblPayments = new JLabel("Payments Made: ");
paymentsPanel.add(lblPayments);
paymentsPanel.add(paymentsMade);
getContentPane().add(paymentsPanel);

// Add output with scroll bars and operation chooser
getContentPane().add(opChooser);
JScrollPane outputScroll= new JScrollPane(output,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(outputScroll);


setSize(500,400);
show();
}

lunchboxtheman
Apr 3rd, 2007, 08:13 PM
EDIT: Check out the flowlayout (http://java.sun.com/j2se/1.4.2/docs/api/java/awt/FlowLayout.html). I find it to be a little bit easier to use than the boxlayout.

Aligning components in Java I have found to be one of the most aggravating tasks of making a GUI (I don't like using WYSIWYG editors).