简体   繁体   中英

Java Swing: SpringLayout within BorderLayout

I'm having problems with my GridLayout whereby a JTextField widens to fit an entry longer than the initial size. Another poster with this problem was told SpringLayout was the easiest solution, so that's what I'm trying. However I'm having problems getting this panel to even display.

I've top, bottom, left, and right panels each with different layouts that are set in a top-level panel (the only one in this frame). This SpringLayout I'm trying is to be in the right panel (added to the top panel as topPanel.add(springPanel, BorderLayout.EAST - this was how I did it when this panel was a GridLayout). The code below is modeled after the SpringLayout Oracle tutorial. Sorry I'm new to this layout and am only using it to use fixed widths for JTextFields.

JPanel testPanel = new JPanel();
SpringLayout layout = new SpringLayout();
testPanel.setLayout(layout);
JLabel label = new JLabel("First field: ");
JTextField field = new JTextField("enter text");

testPanel.add(label);
testPanel.add(field);

layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, testPanel);
layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, testPanel);
layout.putConstraint(SpringLayout.WEST, field, 5, SpringLayout.EAST, label);
layout.putConstraint(SpringLayout.NORTH, field, 5, SpringLayout.NORTH, testPanel);

...

topPanel.add(testPanel, BorderLayout.EAST);

Any guidance would be appreciated. Thanks.

EDIT: Adding the cols argument doesn't seem to work, but I'll keep trying. The same problem exists with GridBagLayout. Tabbing to the next field doesn't re-size the previous field, but clicking outside those fields elsewhere in the frame causes it to expand the length of its containing text which is what I need to avoid. And I don't have enough rep pts to post images of what I'm doing

EDIT2: Adding cols works - I tried that at some point. Not entirely sure how it's working, but any value (1, 10, 15 tested) seems to fix the length so leaving that panel's focus no longer causes a size change. Thanks!

@Andrew Thompson's answer worked - use col arg to specify # of columns (any number seems to work). Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM