简体   繁体   中英

Adding JScrollPane to JFrame/JPanel

I looked on many questions and websites but I can not find the answer. I have a JPanel. I would like to add a scroll bar, so I thought I would use a Jscrollpane.

public class TheFrame extends JFrame {

public ThePanel canvas;


public TheFrame() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    setLayout(new BorderLayout());


   //-------------------------------------

    JScrollPane scroll = new JScrollPane(canvas);
    scroll.setViewportBorder(new LineBorder(Color.RED));
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    add(scroll, BorderLayout.SOUTH);

   //-------------------------------------------------


    canvas = new ThePanel();

    setSize(700, 400);

    this.add(canvas, BorderLayout.CENTER);

    setVisible(true); 
}

At the moment, the scroll is just appearing at the bottom. The border shows that it is only a small area at the bottom. I am trying to put the Jpanel into a Jscrollpane. So the border is around the whole application area. ThePanel extends JPanel. Thank you for any assistance.

Add canvas to scroll, and add scroll to this . JScrollPane wraps the component, it doesn't magically add itself to the component.

Example:

JFrame frame = new JFrame();
JPanel pane = new JPanel();
JScrollPane scroller = new JScrollPane(pane);
frame.add(BorderLayout.CENTER, scroller);
scroller.setWheelScrollingEnabled(true);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
frame.setVisible(true);
JScrollPane scroll = new JScrollPane(canvas);
add(scroll, BorderLayout.SOUTH);
canvas = new ThePanel();
this.add(canvas, BorderLayout.CENTER);

A couple of problems:

  1. the canvas variable is null when you create the scrollpane to nothing is added to the scrollpane

  2. a component can only have a single parent so when you add the canvas to the "CENTER" you remove it from the scrollpane.

The structure of the code should be:

canvas = new ThePanel();
JScrollPane scrollPane = new JScrollPane( canvas );
add(scrollPane, BorderLayout.CENTER);
setVisible( true );

That is, you add the canvas to the scrollpane and the scrollpane to the frame.

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