gpt4 book ai didi

java - 使用 GridBagLayout 使 JPanel 子项可滚动

转载 作者:行者123 更新时间:2023-12-01 21:27:43 26 4
gpt4 key购买 nike

我在使 JPanel 组件可滚动时遇到一些问题...我花了 3 个多小时来实现此功能,但没有成功,这就是为什么我请求您的帮助!

窗口类:

public class Window extends JFrame {
public Window(String title) {
super();

Dimension dimension = IHM.getDimension();

this.setTitle(title);
this.setSize(dimension.width, dimension.height);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setMaximumSize(dimension);
this.setMinimumSize(dimension);
this.setContentPane(new Container());
this.setBackground(IHM.getBlue());
this.pack();
this.setVisible(true);
}
}

容器类:

public class Container extends JPanel {
public static Boolean debug = true;
private Dimension lastDimension = new Dimension(0, 0);

public Container() {
// Layout
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();

// Panel configurations
this.setLayout(layout);

/**
* HEADER
*/
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;

this.add(new HeaderPanel(), gbc);

/**
* LEFT
*/
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.BOTH;

JPanel leftPanel = new LeftPanel();

JScrollPane leftPanelScrollable = new JScrollPane(leftPanel);

leftPanelScrollable.setViewportView(leftPanel);
leftPanelScrollable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
leftPanelScrollable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
leftPanelScrollable.setBounds(10, 10, leftPanel.getWidth() - 50, leftPanel.getHeight() - 50);

this.add(leftPanelScrollable, gbc);

// ...
}
}

还有 leftPanel 类:

public class LeftPanel extends JPanel {
private static Dimension dimension = new Dimension(IHM.getWidth() / 2, IHM.getHeight() - 220);

public LeftPanel() {
this.setPreferredSize(dimension);

// Add the labels
this.addLabel();

// Add the radios
this.addRadios();

this.setAutoscrolls(true);
}
}

请查看屏幕截图,我没有任何滚动条:(

结果如图:

/image/q40Ct.png

你对这个问题有什么想法吗?提前致谢!

最佳答案

leftPanelScrollable.setBounds(10, 10, leftPanel.getWidth(), leftPanel.getHeight());

这应该会造成损害。上述方法强制 JScrollPane 与底层面板的大小相同。让布局管理器来完成工作。

附注我还没有测试过。

<小时/>

您还应该尝试让您的 JPanel 实现 Scrollable并设置

public boolean getScrollableTracksViewportHeight()

还有

public boolean getScrollableTracksViewportWidth()

返回错误。

关于java - 使用 GridBagLayout 使 JPanel 子项可滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37823057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com