1 回答

TA貢獻1775條經(jīng)驗 獲得超8個贊
我在嘗試解決這個問題時遇到了兩個不同的問題。第一個是將JScrollPane包含在窗口內(nèi),第二個是JScrollPane動態(tài)調(diào)整 的大小。
我能夠解決第一個問題,但無法使用自定義類完全解決第二個問題。隨著窗口的增加動態(tài)JScrollPane增加其寬度,但不會隨著窗口大小動態(tài)縮小。這是因為當窗口尺寸減小時,outerJScrollPane會鎖定內(nèi)部內(nèi)容的寬度,包括inner JScrollPane。
我無法找到一種方法讓內(nèi)部窗格動態(tài)收縮,而無需有效刪除外部窗格的功能,這是行不通的,因為您的問題是專門針對另一個功能內(nèi)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();
}
}
添加回答
舉報