简体   繁体   中英

Java Swing: adding ScrollPane to JPanel

Trying to add a vertical scroll bar to one of the panels in my user interface. Nothing is happening. Related segment below:

outputPanel= new JPanel();      
outputPanel.setLayout(null);
outputPanel.setBackground(Color.decode("#ecb3ff"));
scrollPane= new JScrollPane(outputPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(700,700));  
scrollPane.setViewportView(outputPanel);        
frame.add(scrollPane);

scrollPane.setVisible(true);
outputPanel.setLayout(null);

Don't use a null layout.

The scrollbar will only appear when the preferred size of the component added to the viewport is greater than the size of the scrollpane.

The preferred size is only calculated when you use layout managers. Since you don't use a layout manager the preferred size is (0, 0) so there is no need to display an active scrollbar.

Read the Swing tutorial on Layout Managers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM