0

I want to have a list of text fields and labels aligned vertically on a panel with each label corresponding to the appropriate text field and appearing beside it on the UI. The value in the text field will be later called for another function.

The problem is that I can't seem to get the layout right. I have tried using Spring Layout but I can't get my head around it......Basically can I do this any other way? I'm currently using box layout for the panel but it only shows up a list of text fields with a list of labels underneath it. I'm still a noob and I really need some fresh input on this. Any help would be very much appreciated, thanks.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    `I have tried using Spring Layout but I can't get my head around it......` - Did you read the Swing tutorial on [How to Use SpringLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html)? It contains a working example. Start with the working example and make your changes. Having said that, there are easier layout managers to use, but the place to start is with the tutorial for the basics. Then if there is something you don't understand you can post a specific question rather than just saying "it doesn't work". – camickr Jun 29 '14 at 23:53

2 Answers2

3

You could simply use GridBagLayout (although MigLayout might worth a look as well)...

setLayout(new GridLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < 10; index++) {
    gbc.anchor = GridBagConstraints .EAST;
    gbc.gridx = 0;
    add(new JLabel("Label " + index), gbc);
    gbc.anchor = GridBagConstraints .WEST;
    gbc.gridx++;
    add(new JTextField(10), gbc);
    gbc.gridy++;
}

Now, obviously, this is just an example used to demonstrate the concept, you'll need to expand the idea and apply it to your particular problem...

Take a look at How to use GridBagLayout for more detaols

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

I would suggest to have a look at RiverLayout manager. It is really simple and straightforward to use.

http://www.datadosen.se/riverlayout/

JFrame frame = new JFrame("Test RiverLayout");
Container container = frame.getContentPane();
container.setLayout(new RiverLayout());
container.add("left", new JLabel("Label 1"));
container.add("tab", new JTextField("Text field 1"));

container.add("br left", new JLabel("Label 2"));
container.add("tab", new JTextField("Text field 2"));

frame.pack();
frame.setVisible(true);
Rami
  • 7,162
  • 1
  • 22
  • 19