[英]JPanel inside JScrollPane: Vertical bar is not appearing
我的JFrame有一個中央面板,該面板的寬度和高度比屏幕的尺寸要大,我希望這個中央面板顯示在JScrollPane內,現在的問題是垂直滾動條沒有出現。 JScrollPane僅顯示其水平位置,而不顯示垂直位置。 以下是我的JFrame的代碼。
import java.awt.*;
import javax.swing.*;
public class TestScroll extends JFrame {
public TestScroll() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width,screenSize.height);
getContentPane().setLayout(new BorderLayout());
JPanel centerPanel=new JPanel(new BorderLayout());
centerPanel.setSize(screenSize.width+50,screenSize.height+50);//I want centralPanel to be of more width and height so to test JScollPane
JPanel northPanel = new JPanel();
Dimension d1=centerPanel.getSize();
northPanel.setPreferredSize(new Dimension(d1.width,d1.height/3));
northPanel.setBackground(Color.BLACK);
centerPanel.add(northPanel, BorderLayout.NORTH);
JPanel innerPanel = new JPanel();
//Dimension d1=centerPanel.getSize();
//panel2.setPreferredSize(new Dimension(d1.width,d1.height/2));
innerPanel.setBackground(Color.ORANGE);
centerPanel.add(innerPanel, BorderLayout.CENTER);
JScrollPane pane=new JScrollPane(centerPanel);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(pane, BorderLayout.CENTER);
this.setVisible(true);
}
public static void main(String[] args) {
new TestScroll();
}
}
請幫助我顯示垂直滾動條。
在Swing中,您可以通過多種方式進行組件布局:手動完成所有操作或使用LayoutManager。
僅當您在容器內不使用LayoutManager
時,才調用setSize()
起作用。 面板基本上會根據其容器(您的窗口)的大小進行調整,並且沒有所需的大小,因為它不是管理組件大小的setSize()
方法,而是BorderLayout管理器。
但是,如果您在面板上填充的內容大於屏幕尺寸,則會出現滾動條。
您可以重寫組件的getPreferredSize()
,以便它返回所需的尺寸,如此處和此處所示。
如果即使組件的大小不超過JScrollPane,也希望顯示滾動條,則可以將其設置為:
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
您可以使用此innerPanel.setPreferredSize(new Dimension(d1.width,2*(d1.height/3)));
查看垂直滾動條。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.