我在JPanel
中使用了JEditorPane
,我在下面的示例中称其为contentPane
。内容窗格位于JScrollPane
内。我希望编辑器窗格填充尽可能小的空间(只是包含它的文本),而内容窗格中剩余的可用空间留空到底部和任意一侧。如果文本太大,编辑器窗格会增大,最终滚动窗格将创建滚动条来浏览所有内容。但是,编辑器窗格只会占用其首选大小(即其包含的文本的大小),而不会填充整个内容窗格,该窗格将填充滚动窗格的整个视图端口。下面是一些例子代码来证明我的问题:JEditorPane填充JScrollPane中的所有可用空间
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
@SuppressWarnings("serial")
public class ScrollPaneExample extends JFrame {
public static void main(String[] args) {
new ScrollPaneExample();
}
public ScrollPaneExample() {
super("ScrollPaneExample");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JEditorPane editorPane = new JEditorPane("text/plain", "");
editorPane.setBackground(Color.YELLOW);
for (int i = 0; i < 5; i++)
editorPane.setText(editorPane.getText() + "Hello World\n");
JPanel contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.setBackground(Color.BLUE);
contentPane.add(editorPane);
JScrollPane scrollPane = new JScrollPane(contentPane);
add(scrollPane, BorderLayout.CENTER);
setVisible(true);
}
}
运行时,这个窗口是什么样子:
通过黄色的背景下,我们可以看到,在编辑器窗格正在所有的空间。下面是我想要的布局看起来像一个(Photoshop处理)例如:
蓝色的背景代表内容窗格中,黄色代表编辑窗格。
编辑:在我的工作程序中,contentPane
不仅仅是一个编辑器窗格。这就是为什么我使用BoxLayout
代替contentPane
的FlowLayout
;因为需要垂直页面流布局。
是如何确定的大小?你想要这个确切的大小(意味着适合五个你好世界)?你想要一个特定的尺寸?你想要基于动态文本的大小吗? – 2014-08-31 20:03:46
@peeskillet编辑器窗格应根据文本动态更改大小。适合输入的任何文本。 – 2014-08-31 20:12:54
你想要在滚动窗格中的视图动态调整大小(基本上整个滚动窗格 - 哪一个击败滚动窗格的prupose)?或视图保持不变,但卷轴添加?在后一种情况下,什么是确定初始大小,五个hello世界的内容? – 2014-08-31 20:15:18