JScrollPane is not Working in JPanel

折月煮酒 提交于 2020-01-30 08:25:13

问题


I have to use JScrollPane in my Project but it is not working.

I have pasted my code where I use a JSCrollPane in my main JPanel.

frame = new JFrame();
        frame.setBounds(100, 100, 1179, 733);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setBounds(0, 0, 1163, 694);
        frame.getContentPane().add(scrollPane_1);

        JPanel panel = new JPanel();
        scrollPane_1.setViewportView(panel);
        panel.setLayout(null);

回答1:


Setting the layout to Null means you need to handle the placement manually --> Specify the pixel location and handle the size of the container.

A layout manager handles this placement for you. The manager calculates its preferred size based on its content. The ScrollPane uses this calculated size from the layout manager.

This means you should use a layout manager, place your components within it. The rest should work automatically.

 public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(30, 15));
    for (int row = 0; row < 30; row++) {
        for (int col = 0; col < 15; col++) {
            panel.add(new Button("Button" + row + "/" + col));
        }
    }

    frame.getContentPane().add(new JScrollPane(panel));
    frame.setVisible(true);
}



回答2:


I am not sure which layout you are using, but you need to set your panel layout something like this

panel.setLayout(new FormLayout(
                        "default:grow",
                        "fill:default:grow"));


来源:https://stackoverflow.com/questions/44450172/jscrollpane-is-not-working-in-jpanel

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