我有一个示例面板,其中有其他组件,在我的例子中是 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);
}
}
而且我不想要 JTextArea 的滚动条。我希望它的高度与完整查看其内容所需的高度相同。
最佳答案
除非文本区域的大小已知,否则无法确定文本区域的首选大小。也就是说,在知道文本区域的宽度之前,无法完成文本的换行。所以你需要给文本区域一个宽度。
此外,您不能为面板指定首选尺寸,因为这会违背使用 pack() 的目的;
// setPreferredSize(new Dimension(300, 85));
...
textArea.setText(text);
textArea.setSize(300, 1);
关于java - 增加 JPanel 的高度及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7962075/