用其内容增加JPanel的高度

时间:2011-11-01 03:14:15

标签: java swing jpanel jtextarea

我有一个示例面板,其中包含其他组件,在我的例子中是JTextArea。我想增加面板的高度,因为JTextArea的高度增加,固定宽度。我为面板设置了固定宽度。

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);
    }
}

我不想要JAPxtArea的滚动条。我希望它能够获得完全查看其内容所需的高度。

1 个答案:

答案 0 :(得分:4)

除非已知文本区域的大小,否则无法确定文本区域的首选大小。也就是说,在知道文本区域的宽度之前,不能进行文本的包装。所以你需要给文本区域一个宽度。

另外,你不能给面板一个首选大小,因为这会破坏使用pack()的目的;

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