Unable to get JScrollPane working on JFrame

Please check out the small code below. A scroll bar will appear, but the sliders do not. Even if I resize the frame, the sliders will not. Please, help.

import javax.swing.*; public class sample { static JFrame frame; public static void main(String[] args) { String Msg = "Sample Message To Test Scrolling"; frame = new JFrame("Sample Program"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 600); JPanel panel = new JPanel(); panel.setLayout(null); for (int ypos = 0, i = 0; i < 40; i++) { JLabel label = new JLabel("" + i + " " + Msg); label.setFont(new Font("Courier", Font.BOLD, 12)); panel.add(label); label.setBounds(10, ypos + 5, label.getPreferredSize().width, label.getPreferredSize().height); ypos += label.getPreferredSize().height; } JScrollPane scroll = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); frame.setLayout(new BorderLayput()); frame.add(scroll); frame.setVisible(true); } } 
+4
source share
1 answer

Sliders will appear only when and when the component containing the JScrollPane viewport is larger than the viewport. Based on your published code, I don’t understand why your component will be larger than the viewing area, since the panel size will be based on its preferred format, which will never change, since for one you add components to it with it using the zero layout.

Aside, you should almost never use a null layout.

For instance:

 import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.*; public class Sample2 { private static final int PREF_W = 600; private static final int PREF_H = PREF_W; private static final int MAX_ROWS = 400; private static final String TEXT_BODY = "Sample Message To Test Scrolling";; private static void createAndShowGui() { JPanel panel = new JPanel(new GridLayout(0, 1)); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); for (int i = 0; i < MAX_ROWS; i++) { String text = String.format("%03d %s", i, TEXT_BODY); JLabel label = new JLabel(text); panel.add(label); } JScrollPane scrollPane = new JScrollPane(panel); scrollPane.setPreferredSize(new Dimension(PREF_W, PREF_H)); JFrame frame = new JFrame("Sample2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(scrollPane); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } } 
+4
source

All Articles