1 回答
TA贡献1775条经验 获得超8个赞
我在尝试解决这个问题时遇到了两个不同的问题。第一个是将JScrollPane包含在窗口内,第二个是JScrollPane动态调整 的大小。
我能够解决第一个问题,但无法使用自定义类完全解决第二个问题。随着窗口的增加动态JScrollPane增加其宽度,但不会随着窗口大小动态缩小。这是因为当窗口尺寸减小时,outerJScrollPane会锁定内部内容的宽度,包括inner JScrollPane。
我无法找到一种方法让内部窗格动态收缩,而无需有效删除外部窗格的功能,这是行不通的,因为您的问题是专门针对另一个功能内JScrollPane的JScrollPane。
public class TestFrame {
public static void main(String... args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
for (int i = 0; i < 10; i++) {
panel.add(new JButton("Hello-" + i));
}
MyCustomPane scrollPane = new MyCustomPane(panel); //changed this line
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
JPanel contentPane = new JPanel(new BorderLayout());
JPanel contentPaneSub = new JPanel();
contentPaneSub.add(scrollPane);
scrollPane.setOuterContainer(contentPaneSub); //added this line
contentPane.add(contentPaneSub, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(new JButton("Example"));
contentPane.add(centerPanel, BorderLayout.CENTER);
JScrollPane scrollPane1 = new JScrollPane(contentPane);
scrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
frame.setContentPane(scrollPane1);
//for demo purpose we set this using hard coded way
//in real life project the java will auto adjust it size based on windows resolution
frame.setSize(new Dimension(500, 160));
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
MyCustomPane 类的代码:
public class MyCustomPane extends JScrollPane {
Container outerContainer;
public MyCustomPane(Component view) {
super(view);
}
public void setOuterContainer(Container outerContainer) {
this.outerContainer = outerContainer;
}
private Dimension getCustomDimensions() {
if (outerContainer == null) {
return new Dimension(0, 0);
}
return new Dimension(outerContainer.getWidth() - 10, 60); //10 pixels less than container width, arbitrary height
}
@Override
public Dimension getMaximumSize() {
return getCustomDimensions();
}
@Override
public Dimension getMinimumSize() {
return getCustomDimensions();
}
@Override
public Dimension getPreferredSize() {
return getCustomDimensions();
}
}
添加回答
举报