Reputation: 5
I need to align components (2 JTextField
s and 1 JTextArea
) vertically in a JPanel
, then position this panel in center of a already defined frame.
I want exactly like this.
I tried to do this by setting different layouts to panel, but I cannot get it to work. In the code below, it is fine without anything anything to the panel. If I add components to the panel it behaves differently. The components are displayed horizontally in the panel.
public class DialogboxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example X_AXIS");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel lblPhone = new JLabel("Name");
lblPhone.setBounds(65, 68, 46, 14);
frame.getContentPane().add(lblPhone);
JTextField textField_1 = new JTextField();
textField_1.setBounds(136, 65, 247, 22);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JLabel lblEmailId = new JLabel("Category");
lblEmailId.setBounds(65, 115, 70, 14);
frame.getContentPane().add(lblEmailId);
JTextField textField_2 = new JTextField();
textField_2.setBounds(136, 112, 247, 22);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JLabel lblAddress = new JLabel("Description");
lblAddress.setBounds(65, 162, 150, 14);
frame.getContentPane().add(lblAddress);
JTextArea textArea_1 = new JTextArea();
textArea_1.setBounds(136, 157, 300, 100);
frame.getContentPane().add(textArea_1);
frame.setSize(300, 300);
frame.getContentPane().add( panel, "Center");
frame.pack();
frame.setVisible(true);
}
}
I want the JTextField
s and the JTextArea
to be stacked vertically.
Can someone please help me on this?
If I add a GridLayout
to the panel it works well, but the component size is same for all 3 components.
Upvotes: 0
Views: 128
Reputation: 168845
GridBagLayout
(not a GridLayout
) for the labels and text fields / area), then put that panel in another GridBagLayout
to center it in the JFrame
. (If I understand the requirement correctly, which I'm not certain I do.) JLabel
for the Description
as opposed to a TitledBorder
. setBounds(..)
will be ignored using any layout worth using. Specify columns to suggest a width for text fields and columns and rows for a text area. DialogboxExample
is not very accurate, given a JFrame
is used to display the GUI. It's likely it should instead be using a JDialog
, but sticking with the frame might result in something like this:Upvotes: 1