JScrollPane doesn't show scroll bars when JPanel is added

空扰寡人 提交于 2021-01-28 01:45:20

问题


I'm tried to add a JPanel to a JScrollPane using:

    panel1 Panel1 = new panel1(); 
    jScrollPane1.setViewportView(Panel1);

and it worked. But the problem is scrollPane doesn't show scroll bars even the Panel1 is bigger. (I'm working with NetBeans & panel1 is a jpanel form)


回答1:


Override, getPreferredSize() method for the said JScrollPane, you might be able to see the Scroll Bar. Or one can simply call setPreferredSize(), though as stated in the API

Sets the preferred size of this component. If preferredSize is null, the UI will be asked for the preferred size

overriding will be beneficial, as it tends to define some appropriate dimensions to the said JComponent.

Something like this:

JScrollPane scroller = new JScrollPane() {
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 200);
    }
};
scroller.setViewportView(panelWithScroll);

One example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PanelScroller {

    private void displayGUI() {
        JFrame frame = new JFrame("Swing Worker Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        JPanel panelWithScroll = new JPanel();
        panelWithScroll.setLayout(new GridLayout(0, 1, 5, 5));
        JScrollPane scroller = new JScrollPane() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 200);
            }
        };
        scroller.setViewportView(panelWithScroll);
        //scroller.setPreferredSize(new Dimension(300, 200));

        for (int i = 0; i < 20; i++) {
            panelWithScroll.add(new JLabel(Integer.toString(i + 1), JLabel.CENTER));
        }

        contentPane.add(scroller);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new PanelScroller().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}



回答2:


If you only want the scrollbars to show up you can call

JScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

But that don't make them work at all.

if you wont to make them work you can try to set the preferred size of the component inside the Scrollpane to larger then size of Scrollpane and then call repaint(e.g. by make the window fullscreen)



来源:https://stackoverflow.com/questions/24639132/jscrollpane-doesnt-show-scroll-bars-when-jpanel-is-added

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!