Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - JScrollPane view layout with SpringLayout

I have a JScrollPane that has a view component which uses SpringLayout.

final JPanel panel = new JPanel(new SpringLayout());
// add stuff to panel here
final JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
getContentPane().add(scrollPane);

The JScrollPane doesn't seem to work, any help would be greatly appreciated!

like image 479
Ramus Avatar asked Jun 12 '26 00:06

Ramus


1 Answers

Quoting from How to Use Scroll Panes

Unless you explicitly set a scroll pane's preferred size, the scroll pane computes it based on the preferred size of its nine components (the viewport, and, if present, the two scroll bars, the row and column headers, and the four corners). The largest factor, and the one most programmers care about, is the size of the viewport used to display the client.

  • so you would have to either call setPreferedSize(Dimension d) on JScrollPane instance

    final JPanel panel = new JPanel(new SpringLayout());
    // add stuff to panel here
    final JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(300, 300));
    add(scrollPane);
    
  • or override getPreferredSize() of your JPanel/ component used as view port

    final JPanel panel = new JPanel(new SpringLayout()) {
    
        @Override
        public Dimension getPreferredSize() {
             return new Dimension(300, 300);
         }
     };
     // add stuff to panel here
     final JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    add(scrollPane);
    

Other notes:

  • do not extend JFrame class unnecessarily.

  • simply call add(..) on JFrame instance as the call is forwarded to contentPane.

like image 73
David Kroukamp Avatar answered Jun 14 '26 03:06

David Kroukamp