我正在构建一个充满标签的网格。其中之一包含 html 文本,应将大小调整为最大格式并且可滚动。我找到了如何添加 JScrollPane 但它保持一行高度,即使我给它一个 400x400 的大小,我也找不到如何调整它的大小...
删除 getViewport() 会得到相同的结果。
JPanel grid = new JPanel(new GridLayout(1,2));
// first cell of the grid
grid.add(new JLabel("title"));
// second cell of the grid, this should be the scrollable one
JScrollPane scroll = new JScrollPane();
scroll.getViewport().setSize(400, 400);
scroll.getViewport().add(new JLabel("<html>long<br>html<br>text</html>"));
grid.add(scrollVersion, BorderLayout.CENTER);
有什么想法吗?
非常感谢...
最佳答案
GridLayout 不考虑其布局的组件的首选大小。它的目的是使所有网格单元具有相同的大小。另一种方法是使用 GridBagLayout,但我个人会推荐 ZoneLayout (在我看来)它更简单,同样强大,而且更直观。随着cheatsheet你不会出错的。
顺便说一句,BorderLayout.CENTER 是用于 BorderLayout 的约束,与 GridLayout 不兼容。将组件添加到 GridLayout 的所有者时,无需提供约束。使用 GridLayout 从左上角单元格开始从左到右添加组件。
关于java - 将可滚动 jpanel 添加到网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3279991/