嘿,我是新手
我希望动态内容与父窗口一样宽(并自动根据其宽度调整大小),但能够在需要时向下滚动(如果内容超出可用空间)。我正在向 JScrollPanel
添加和删除多个内容,例如 Jpanel
或 JinternalFrame
。
大多数事情,无论是自定义类还是布局管理器,我尝试过,要么只隐藏滚动条(但不会阻止永远在水平方向添加内容) 或者只是缩小了内容。
我试过https://tips4java.wordpress.com/2009/12/20/scrollable-panel/ 但它只会拉伸(stretch)或收缩public class MainView extends JFrame {
private ScrollablePanel contentPane;
private JScrollPane scrollPane;
...
在构造函数中:
...
contentPane = new ScrollablePanel(new BorderLayout());
contentPane.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.NONE);
contentPane.setScrollableHeight(ScrollablePanel.ScrollableSizeHint.NONE);
contentPane.setBorder(new EmptyBorder(1, 1, 1, 1));
scrollPane = new JScrollPane(contentPane);
setContentPane(scrollPane);
不同的尺寸提示或布局(例如默认 Flowlayout)要么更差,要么相同
垂直滚动按预期工作,但不限制水平方向的内容(似乎我不允许添加屏幕截图) 我不需要这个类,如果你认为它可以以其他方式实现
最佳答案
不久前我遇到了类似的问题,并且能够使用自定义 JPanel 解决它:
/**
* A panel that can be used in a JScrollPane which always adapts to the
* width of the JScrollPane (so only vertical scrolling will happen).
*/
public class ParentWidthPanel extends JPanel implements Scrollable {
private static final long serialVersionUID = 1L;
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
@Override
public int getScrollableUnitIncrement(final Rectangle visibleRect, final int orientation, final int direction) {
return 5;
}
@Override
public int getScrollableBlockIncrement(final Rectangle visibleRect, final int orientation, final int direction) {
return 15;
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
@Override
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return ((getParent()).getHeight() > getPreferredSize().height);
}
return false;
}
}
要点是让方法 getScrollableTracksViewportWidth()
返回 true
。
关于java - 动态添加内容时将 Jscrollpanes 宽度限制为父级宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56127486/