简体   繁体   English

将JScrollPane添加到JFrame / JPanel

[英]Adding JScrollPane to JFrame/JPanel

I looked on many questions and websites but I can not find the answer. 我查看了许多问题和网站,但找不到答案。 I have a JPanel. 我有一个JPanel。 I would like to add a scroll bar, so I thought I would use a Jscrollpane. 我想添加一个滚动条,所以我想使用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. 我正在尝试将Jpanel放入Jscrollpane。 So the border is around the whole application area. 因此边界遍布整个应用程序区域。 ThePanel extends JPanel. ThePanel扩展了JPanel。 Thank you for any assistance. 感谢您的协助。

Add canvas to scroll, and add scroll to this . 添加画布进行滚动,然后将滚动添加this JScrollPane wraps the component, it doesn't magically add itself to the component. JScrollPane包装组件,它不会神奇地将自身添加到组件中。

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 当您创建滚动窗格时canvas变量为null,没有任何内容添加到滚动窗格

  2. a component can only have a single parent so when you add the canvas to the "CENTER" you remove it from the scrollpane. 一个组件只能有一个父对象,因此将画布添加到“ CENTER”时,会将其从滚动窗格中删除。

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. 也就是说,您将画布添加到滚动窗格,并将滚动窗格添加到框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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