简体   繁体   English

为什么我的JScrollPane不显示我的JPanel?

[英]Why doesn't my JScrollPane shows my JPanel?

I have a JPanel and I want it to be able to be scrolled, so I am adding it to a JScrollPane, but my JScrollPane doesn't show my Panel completely. 我有一个JPanel,希望它能够滚动,因此我将其添加到JScrollPane中,但是我的JScrollPane不能完全显示我的面板。 just a very small corner of it is shown and it doesn't scrollit either. 只是显示了它的一个很小的角,它也没有滚动。 But when I only add the LPanel to my JFrame, it is shown correctly! 但是,当我仅将LPanel添加到我的JFrame时,它可以正确显示! Can someone tell me what am I doing wrong here? 有人可以告诉我我在做什么错吗?

Info about my code: 有关我的代码的信息:

  • LPanel is extended from JPanel and I have override the paint. LPanel是从JPanel扩展而来的,我已经覆盖了绘画。 but as I said, the paint works fine! 但正如我所说,油漆效果很好! it has it's own width and height that are 2^k. 它有自己的宽度和高度为2 ^ k。
  • k is the number of rows in my panel. k是面板中的行数。

This is my code: 这是我的代码:

public class Graphics extends JFrame {
  LPanel panel;
  int k;
  public Graphics(int k1) {
    setLayout(null);
    this.k = k1;
    panel = new LPanel(k);
    panel.setSize(panel.width * 30, panel.height * 30);
    new CoveringwithLs(k, panel);
    JScrollPane pane = new JScrollPane(panel);
    pane.setLocation(20, 20);
    if (k < 4) {
      pane.setSize(panel.width * 30, panel.height * 30);
      this.setSize(panel.width * 30 + 80, panel.height * 30 + 80);
    } else {
      pane.setSize(panel.width * 30, 600);
      this.setSize(panel.width * 30 + 80, 600);
    }
    getContentPane().add(pane);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }
  public static void main(String[] args) {
    new Graphics(3);
  }
}

Can anyone help me? 谁能帮我?

I cant add an example, 我无法添加示例,

Of course you can. 当然可以。 You already have. 你已经有了。 Now what you need to do is follow the advice given and use layout managers instead of a null layout. 现在,您需要按照给出的建议进行操作,并使用布局管理器代替空布局。

LPanel is extended from JPanel and I have override the paint. LPanel是从JPanel扩展而来的,我已经覆盖了绘画。

Custom painting is done by overriding the paintComponent() method, not the paint() method. 通过覆盖paintComponent()方法而不是paint()方法来完成自定义绘制。

it has it's own width and height that are 2^k. 它有自己的宽度和高度为2 ^ k。

You need to override the getPreferredSize() method of your panel to return the dimension. 您需要重写面板的getPreferredSize()方法以返回尺寸。 Then the scrollpane will function correctly. 然后,滚动窗格将正常运行。

Have you added the scrolls to the ScrollPane. 您是否已将滚动条添加到ScrollPane。 eg 例如

 JScrollPane pane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

You need to set the preferred size for your JPanel, otherwise the JScrollPane does not know how big is the component it needs to support with its scroll bars. 您需要为JPanel 设置首选大小 ,否则JScrollPane不知道它需要用滚动条支持的组件有多大。 setSize has a different purpose and in this cas is not enough. setSize具有不同的用途,在此cas中还不够。

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

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