简体   繁体   中英

How to add a ScrollBar at the bottom of the JPanel when using GridLayout?

Hello i wanted to know how to add a ScrollBar at the bottom of a JPanel if i use GridLayout in my desktop app, as far as i know GridLayout only accept as parameter quantity of colums, rows and the horizontal and vertical gap. So how can i add a scroll bar and use it to see the information that's in the JPanel?

Put the JPanel with GridLayout into a JScrollPane . EG as seen with the two column GridLayout that displays the labels added to the nested layout example .

If you want the JSrollBar to scroll the JPanel with the gridlayout, then put the grid layout into a scrollpane (remember to extend the scrollable interface)

Read this page of the tutorial to learn how to.

IF you want to use the events from the JScrollBar to change the visible area of your panel then put the panel inside another panel with a JScrollbar on the bottom.

This is an example with a green panel and a scrollbar at the bottom

public class Window extends JFrame {

    public Window() {
        setPreferredSize(new Dimension(500, 500));
        setMinimumSize(new Dimension(500, 500));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(100, 100));
        panel.setBackground(Color.GREEN);
        getContentPane().add(panel, BorderLayout.CENTER);

        JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
        scrollBar.setMinimum(0);
        scrollBar.setMaximum(100);
        scrollBar.setBlockIncrement(30);
        scrollBar.addAdjustmentListener(new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                 System.out.println("Adjustment changed");
            }
        });
        getContentPane().add(scrollBar, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Window();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM