2014-07-10 54 views
0

我的JFrame有一个中央面板,它的宽度和高度都比屏幕尺寸大,我希望这个中央面板显示在JScrollPane里面,现在问题出现在没有出现的垂直滚动条中。 JScrollPane只显示其水平位置不垂直。以下是我的JFrame的代码。JScrollPane中的JPanel:没有出现竖线

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(); 
    } 

} 

请帮我显示垂直滚动条..

+0

可能[重复](http://stackoverflow.com/q/9092198/230513)。 – trashgod

回答

2

在Swing中,你有组件布局的几种方法:手工做的一切,或使用一个LayoutManager。

调用setSize()只有当您的容器内没有使用LayoutManager时,才能正常工作。面板基本上根据其容器的大小(窗口)进行调整,并且没有您想要的大小,因为它不是控制组件大小的方法,而是您的BorderLayout管理器。

但是,如果您的面板填充的内容大于屏幕大小,则会出现滚动条。

您可以覆盖组件的getPreferredSize(),以便返回所需的尺寸,如herehere所示。

如果你想显示滚动条,即使在不超过JScrollPane的大组件,可以将其设置liek这样的:

pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
+0

好点,我编辑答案 – Smajl

0

您可以使用此 innerPanel.setPreferredSize(new Dimension(d1.width,2*(d1.height/3)));看到垂直滚动条。

+0

好克里斯!你的回答是正确的 – user3741146

+0

@ user3741146:如果你发现这个答案有帮助,你可以接受它或投票了。 –