Java Swing:如何将多个 JPanel 添加到 JScrollPane [英] Java Swing: how to add multiple JPanels to a JScrollPane

查看:57
本文介绍了Java Swing:如何将多个 JPanel 添加到 JScrollPane的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网上我读到要向 JscrollPane 添加组件,我们必须执行:

On the net I read that to add a component to a JscrollPane we must perform:

scrollPane.getViewport().setView(jpanel);

好吧,这是我的代码.为了显示多个组件,在本例中为 JButton,我尝试将它们添加到多个 JPanel 中,并在最后按顺序添加这些组件.但只显示最后一个 JPanel.为什么?

Well, this is my code. To show multiple components, in this case JButtons, I am trying to add them into multiple JPanels and add these last in order at the end. But only the last JPanel is shown. Why?

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import layout.TableLayout;

public class Main {

  public static void main(String argv[]) {

      JFrame jframe = new JFrame("Protocollo UTL");
      jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jframe.setSize(1200, 450);

      JPanel body = new JPanel();
      double[][] size = {
            {0.05},
            {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}

      };

      body.setLayout(new TableLayout(size));

      for(int i=0; i<19; i++) {
          body.add(new JButton(String.valueOf(i)), "0,"+String.valueOf(i));
      }

      JPanel body2 = new JPanel();
      body2.setLayout(new TableLayout(size));


      for(int j=0; j<6; j++) {
          body2.add(new JButton(String.valueOf(j)), "0,"+String.valueOf(j));
      }

      JScrollPane scrollPane = new JScrollPane(body,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

      scrollPane.getViewport().setView(body);
      scrollPane.getViewport().setView(body2);

      jframe.add(scrollPane);
      jframe.setVisible(true);

  }

}

推荐答案

您正在用第二个语句覆盖第一个语句

You are overriding the first one with the second statement

scrollPane.getViewport().setView(body);
scrollPane.getViewport().setView(body2);

您应该将两个 JPanel 都添加到某个父组件,并将该组件设置为视图.像这样:

You should add both JPanels to some parent component, and set that component as view. Something like this:

Container cont = new Container();
cont.add(body);
cont.add(body2);
scrollPane.getViewport().setView(cont);

编辑

我认为您根本不需要那行 (setView(...)).试试这个(把这个而不是最后四行)

I don't think you need that line (setView(...)) at all. Try this (put this instead of last four lines)

  Container cont = new Container();
  cont.add(scrollPane);
  cont.add(body2);
  cont.setLayout(new GridLayout());

  jframe.add(cont);
  jframe.setVisible(true);

这篇关于Java Swing:如何将多个 JPanel 添加到 JScrollPane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆