Search code examples
javaswingjpaneljtextarea

increase height of JPanel with its content


I have a sample panel which have other component, in my case JTextArea. I want to increase the height of the panel as the height of JTextArea increases, with fixed width. I have set fixed width for panel.

public class Panel extends JPanel {

    public Panel() {
        setPreferredSize(new Dimension(300, 85));
        setLayout(new BorderLayout());
        JPanel pic = new JPanel(new FlowLayout(FlowLayout.LEFT));
        pic.setBackground(Color.GRAY);
        pic.add(new JLabel(new ImageIcon("img/icon.png")));




        JPanel status = new JPanel(new FlowLayout(FlowLayout.LEFT));
        status.setBackground(Color.GRAY);

        JTextArea textArea = new JTextArea();

        String text = "The quick brown fox jumps over the lazy dog. "
                + "The quick brown fox jumps over the lazy dog. "
                + "The quick brown fox jumps over the lazy dog. "
                + "The quick brown fox jumps over the lazy dog. "
                + "The quick brown fox jumps over the lazy dog. "
                + "The quick brown fox jumps over the lazy dog. "
                + "The quick brown fox jumps over the lazy dog.";
        textArea.setText(text);
        textArea.enable(false);

        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        add(textArea);
        status.add(textArea);

        add(pic, BorderLayout.WEST);
        add(status, BorderLayout.CENTER);

        setBorder(BorderFactory.createEtchedBorder());
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Panel Test");

        f.add(new Panel());

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

And I don't want scrollbar for JTextArea. I want it to take as much height as it takes for complete viewing of its content.


Solution

  • The preferred size of the text area can't be determined unless the size of text area is known. That is the wrapping of the text can't be done until the width of the text area is known. So you need to give the text area a width.

    Also, you can't give the panel a preferred size since this will defeat the purpose of using pack();

    // setPreferredSize(new Dimension(300, 85));
    ...
    textArea.setText(text);
    textArea.setSize(300, 1);