0

I have this problem.

I've already added JPanel to JScrollPane but the scrollbar is not working

Here is my code for JPanel and some picture:

    JPanel panel = new JPanel();
    panel.setBorder(new TitledBorder(null, "Choose table",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel.setLayout(null);

    // Add 10 table
    for (int i = 1; i <= 15; i++) {
        JLabel ban = new JLabel(new ImageIcon(getClass().getResource("/images/table-32-green.png")));
        ban.setOpaque(true);
        ban.setText("Table " + (i));
        ban.setBounds(20, (5 + 70) * i, 65, 60);
        ban.setHorizontalTextPosition(SwingConstants.CENTER);
        ban.setVerticalTextPosition(SwingConstants.BOTTOM);
        panel.add(ban);
    }

And here is my JScrollPane:

        JScrollPane scrPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,  
               ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrPane.setBounds(10, 51, 974, 488);
    scrPane.setBorder(BorderFactory.createEmptyBorder());
    getContentPane().add(scrPane);

And here is the picture, there's no scrollbar No scrollbar showed

Please help, thank you very much!

  • *"(why is) Swing JPanel scrollpane not working?"* Because of this `panel.setLayout(null);`, Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Apr 13 '17 at 17:01
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Provide ASCII art or a simple drawing of the *intended* layout of the GUI at minimum size, and if resizable, with more width and height. – Andrew Thompson Apr 13 '17 at 17:01
  • Read MadProgrammer's answer to a similar question. Your panel JPanel uses a null layout, and a this prevents it from changing its preferred size as components are added, which prevents the JPanel from expanding within the JScrollPane. Swing GUI's are meant to be used with layout managers, and using a null layout means you're fighting against the GUI library rather than working with it. The solution is to use a decent layout manager or nested JPanels with decent layout managers. Learn them and use them. – Hovercraft Full Of Eels Apr 13 '17 at 17:04

0 Answers0