How to resize an item in BoxLayout?

I have this class:

package com.erikbalen.game.rpg; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Gui extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = -384241835772507459L; JLabel playerInfo; JTextField textField; private final static String newline = "\n"; JTextArea feed; JScrollPane scrollPane; Player player; public Gui() { super("Erik RPG"); //setLayout(new FlowLayout()); Container contentPane = this.getContentPane(); contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.PAGE_AXIS)); textField = new JTextField(30); textField.addActionListener(this); feed = new JTextArea(15, 30); feed.setEditable(false); scrollPane = new JScrollPane(feed); } 

When you run it, what it does is, it makes the textField really tall if I expand it, although I only want it to be a certain height. How can I

+4
source share
2 answers

BoxLayout expands components to the maximum size, JTextField erroneously returns the maximum height of Short.Max (or Integer.Max, forgot). The way out is to make the field behave:

  @Override public Dimension getMaximumSize() { // TODO Auto-generated method stub Dimension dim = super.getMaximumSize(); dim.height = getPreferredSize().height; return dim; } 

Alternatively use a different LayoutManager :-)

+6
source

The layout manager will reset the size of your component based on various restrictions. You can use the setPreferredSize () method instead of setSize () to tell most layout managers what size the field should be.

eg,

 textField.setPreferredSize(new Dimension(width,height)); 
+2
source

All Articles