2017-06-09 28 views
1

我必须在我的项目中使用JScrollPane,但它不起作用。JScrollPane无法在JPanel中工作

enter image description here

我已经贴上我的代码,我在我的主要的JPanel使用JSCrollPane

frame = new JFrame(); 
     frame.setBounds(100, 100, 1179, 733); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(null); 

     JScrollPane scrollPane_1 = new JScrollPane(); 
     scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
     scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); 
     scrollPane_1.setBounds(0, 0, 1163, 694); 
     frame.getContentPane().add(scrollPane_1); 

     JPanel panel = new JPanel(); 
     scrollPane_1.setViewportView(panel); 
     panel.setLayout(null); 
+3

您的所有问题的主要原因是'setLayout的(空)' - 秋千是围绕布局管理器的概念设计的,它定义了所有用于确定子组件如何在父容器中布局的工作,并一直位于层次结构链中。通过使用'null'布局,你已经抢夺了整个API的能力,以确定组件的大小以及如何对它们做出最好的反应,特别是在使用这些信息做出关于“JScrollPane”的决定的情况下何时显示滚动条 – MadProgrammer

+0

那么,什么是解决方案 –

+2

根据您的需要使用适当的布局管理器 – MadProgrammer

回答

2

将布局设置为Null意味着您需要手动处理布局 - >指定像素位置并处理容器的大小。

布局管理器为您处理这个位置。经理根据其内容计算其首选大小。 ScrollPane使用布局管理器中的这个计算大小。

这意味着您应该使用布局管理器,将组件放入其中。其余的应该自动工作。

public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
    frame.setSize(500, 500); 

    JPanel panel = new JPanel(); 
    panel.setLayout(new GridLayout(30, 15)); 
    for (int row = 0; row < 30; row++) { 
     for (int col = 0; col < 15; col++) { 
      panel.add(new Button("Button" + row + "/" + col)); 
     } 
    } 

    frame.getContentPane().add(new JScrollPane(panel)); 
    frame.setVisible(true); 
} 
0

我不知道哪个布局你正在使用,但你需要设置你的面板布局像这样

panel.setLayout(new FormLayout(
         "default:grow", 
         "fill:default:grow")); 
+0

我已经在框架中使用了7个面板,以便哪种布局适合它 –