【发布时间】:2010-08-14 07:08:58
【问题描述】:
晚上好,
我想知道在 JComponent 使用 LayoutManager 布局后如何获取它的大小。我已经读过这是可能的,如果您事先调用 dolayout()、validate() 或 setVisible()。但是,我无法让它在我的代码中工作。
我想知道这一点的原因是只添加尽可能多的组件以适合框架的设置大小,而事先不知道组件的大小。调用 validate() 不会设置此代码示例中组件的大小。关于如何获得合适尺寸的任何想法?
public class TestFrame extends JFrame {
public static void main(String args[]) {
TestFrame frame = new TestFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public TestFrame() {
super("Test Frame");
super.setSize(300, 600);
this.addComponents();
}
private void addComponents() {
int heightLeft = this.getHeight();
JPanel panel = new JPanel();
panel.setSize(300, 600);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
String text = "This is a long String that represents "
+ "the length of strings in my application. "
+ "This will vary in the real application."
+ "<ul><li>It uses html</li><li>not just</li>"
+ "<li>plain text</li></ul>"
+ "I'd like as many as will fit in the fame to be added.\n";
while (true) {
JTextPane textPane = createTextPane(text);
this.invalidate();
if (heightLeft > 0) {
panel.add(textPane);
} else {
break;
}
System.out.println("Before validation:" + textPane.getSize());
// returns width and height = 0
this.validate();
System.out.println("After validation:" + textPane.getSize());
// Still returns width and height = 0
heightLeft -= textPane.getPreferredSize().getHeight();
}
super.add(panel);
}
public JTextPane createTextPane(String text) {
JTextPane textPane = new JTextPane();
textPane = new JTextPane();
textPane.setEditorKit(new StyledEditorKit());
textPane.setEditable(false);
textPane.setOpaque(false);
textPane.setContentType("text/html");
textPane.setText(text);
return textPane;
}
}
感谢您的宝贵时间!
【问题讨论】:
-
重新格式化的代码;如果不正确,请恢复。
-
JScrollPane会更贴切吗? download.oracle.com/javase/tutorial/uiswing/components/… -
感谢您重新格式化。它看起来更好。 JScrollPane 绝对是我的后备选项。我不认为它看起来太糟糕,但我想出了让应用程序看起来像某种方式的想法,团队中的其他人都非常喜欢这个想法,现在我正试图弄清楚如何这样做:p