我想知道如何獲得一個JComponent的大小,它已經與佈局管理奠定了後。我已經讀過,如果你事先調用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;
}
}
感謝您的時間!
重新格式化的代碼;如果不正確請回復。 – trashgod 2010-08-14 10:43:46
'JScrollPane'會更合適嗎? http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html – trashgod 2010-08-14 10:45:23
感謝您的重新格式化。它看起來更好。 JScrollPane絕對是我的後備選項。我認爲這看起來不會太糟糕,但是我想出了讓應用程序看起來有特定意義的想法,團隊中的其他人都非常喜歡這個想法,現在我一直在試圖弄清楚要做到這一點:p – nova 2010-08-15 04:44:08