Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I change the size of an element in a 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's 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 it it makes the textField really tall if I expand it even though I only want it to be a certain height. How can I

like image 808
Erik Balen Avatar asked Dec 27 '22 14:12

Erik Balen


2 Answers

BoxLayout expands components until their max size, JTextField misbehaves in returning a max 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 another LayoutManager :-)

like image 116
kleopatra Avatar answered Dec 31 '22 14:12

kleopatra


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

for e.g.

textField.setPreferredSize(new Dimension(width,height));
like image 27
Pratik Avatar answered Dec 31 '22 14:12

Pratik