I've been fiddling round with layout managers for a while and can't quite get it to sit the way I want. I figured it's probably something simple but I can't quite seem to see it, so I thought someone else might be able to look at it with a fresh pair of eyes The basic jist of it is that I have a frame with multiple containers on it. It's an order form and I have a container panel that includes 2 JLabels and corresponding JTextFields where the user would type the quantity they wanted. I first tried a basic grid layout and that does almost what I want but the size of the text field is stretched to mirror the size of the item label. I want the text field to be a set size which is independent of the label. Does anyone know how I might do this? Code: // SQUASH RACKET PANEL JPanel squashPanel = new JPanel(); BoxLayout squash = new BoxLayout(squashPanel,BoxLayout.X_AXIS); squashPanel.setLayout(squash); squashTitle = new String("Squash Rackets"); squashBorder = BorderFactory.createTitledBorder(squashTitle); squashPanel.setBorder(squashBorder); string1 = new String("Racket 1 (£000.00) Code xxxxx"); string2 = new String("Racket 2 (£000.00) Code xxxxx"); label1 = new JLabel(string1); label2 = new JLabel(string2); field1 = new JTextField(); field2 = new JTextField(); field1.addActionListener(this); field2.addActionListener(this); squashPanel.setLayout(new GridLayout( 2, 2, 5, 5)); squashPanel.add(label1); squashPanel.add(field1); squashPanel.add(label2); squashPanel.add(field2);
Looks to me that you need GridBagLayout. In essence you'll need to swap the gridwidth between 1 and GridBagLayout.REMAINDER So something like (and I'm just doing this from memory so it may not be 100% correct) Code: JPanel pnl = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.EAST; gbc.gridwidth = 1; pnl.add(label1, gbc); gbc.gridwidth = REMAINDER; // Puts item at end and forces a newline gbc.anchor = GridBagConstraints.WEST; pnl.add(textbox1, gbc); gbc.anchor = GridBagConstraints.EAST; gbc.gridwidth = 1; pnl.add(label2, gbc); gbc.gridwidth = REMAINDER; gbc.anchor = GridBagConstraints.WEST; pnl.add(textbox2, gbc); etc.....