I have a weird problem with laying out some JTextFields.
This code works right:
JPanel setbuttonpanel = new JPanel(); setbuttonpanel.setLayout( new BoxLayout(setbuttonpanel, BoxLayout.LINE_AXIS) ); inputfield = new JTextField(20); setbuttonpanel.add(inputfield); setbuttonpanel.add( Box.createRigidArea( new Dimension(offset, 0) ) ); ... setbutton = new JButton(new SetAction("Set")); setbuttonpanel.add(setbutton); panel.add(setbuttonpanel);
This code does not: (it blows up the textfield's height)
JPanel inputpanel = new JPanel(); inputpanel.setLayout( new BoxLayout(inputpanel,BoxLayout.LINE_AXIS)) ; seedinput = new JTextField(5); amountinput = new JTextField(5); inputpanel.add(seedinput); inputpanel.add(amountinput); panel.add(inputpanel);
How can I fix this so both the textfields and the panel they are in have the size they should have?
This is some compilable code that shows the same problem:
package Test; import java.awt.*; import javax.swing.*; public class TestWindow { private JFrame frame; private JButton randombutton; private JButton savebutton; private JTextField seedinput; private JTextField amountinput; public TestWindow() { frame = new JFrame("Search Simulation"); frame.setPreferredSize(new Dimension(800,600)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int offset = 25; JPanel loadbuttonpanel = new JPanel(); loadbuttonpanel.setBackground(Color.BLUE); loadbuttonpanel.setLayout( new BoxLayout(loadbuttonpanel, BoxLayout.PAGE_AXIS) ); randombutton = new JButton("test"); loadbuttonpanel.add(randombutton); JPanel inputpanel = new JPanel(); inputpanel.setBackground(Color.GREEN); inputpanel.setLayout( new BoxLayout(inputpanel,BoxLayout.LINE_AXIS)); // if you comment out this line they get the right size, but the panel still takes up all the space for some reason seedinput = new JTextField(5); amountinput = new JTextField(5); inputpanel.add(seedinput); inputpanel.add(amountinput); loadbuttonpanel.add(inputpanel); frame.add(loadbuttonpanel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater( new Runnable() { public void run() { TestWindow test = new TestWindow(); } }); } }