我有一个 JScrollPane (两个滚动条都是可选的(不应该导致问题) ScrollPane 内部是一个带有 BoxLayout 和 X_Axis - 对齐的面板。 (它包含任意数量的具有固定(偏好)大小的面板。 问题是 ScrollPane 将比必要的宽得多(水平滚动条滚动通过“灰屏”)。 使用 Y_Axis 对齐,它可以正常工作。 相关代码:
final JPanel forSpecific = new JPanel();
final JScrollPane scrollSpecific = new JScrollPane(forSpecific,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
forSpecific.setLayout(new BoxLayout(forSpecific,BoxLayout.X_AXIS));
我不知道问题是什么,也没有找到任何解决方案......
已编辑:抱歉,花了一些时间。原始代码太复杂,无法提取一些 sscce..我编写了一个测试类。这个例子工作正常..但我不知道有什么不同.. package getdata;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Sscce {
public static void gui(){
final JFrame rootframe = new JFrame("Time Series Mining");
final JPanel mainPanel = new JPanel(new BorderLayout());
rootframe.setSize(new Dimension(400,400));
rootframe.setContentPane(mainPanel);
mainPanel.setLayout(new BorderLayout());
JPanel center=new JPanel(new GridLayout(2,1));
JPanel forSpecific=new JPanel();
forSpecific.setLayout(new BoxLayout(forSpecific, BoxLayout.X_AXIS));
JPanel test1 = new JPanel();
test1.setPreferredSize(new Dimension(1000,1000));
forSpecific.add(test1);
test1.setBackground(Color.white);
final JScrollPane scrollSpecific = new JScrollPane(forSpecific);
center.add(scrollSpecific);
rootframe.add(center, BorderLayout.CENTER);
rootframe.setVisible(true);
}
}
最佳答案
//final JScrollPane scrollSpecific = new JScrollPane(forSpecific,
// ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
// ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
final JScrollPane scrollSpecific = new JScrollPane(forSpecific);
不是问题,而是“根据需要滚动条”是默认设置。您不需要指定这一点。
Inside of the ScrollPane is a panel with BoxLayout and X_Axis - align. (it contains arbitrary number of Panels with fixed (prefference)Size.
什么是固定尺寸?
- 添加到滚动 Pane 的“主”面板
- 添加到主面板的“子”面板
在任何情况下,大小都不应该是固定的,布局管理器应该确定首选大小。或者,如果您正在创建自定义组件,那么您应该重写 getPreferredSize()
方法以返回正确的大小,以便布局管理器可以完成其工作。
关于java - JPanel 以 BoxLayout 和 ScrollPane 作为其父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994418/