将 JPanel 和 JScrollingPane 添加到 JFrame

Adding both a JPanel and JScrollingPane to a JFrame

我目前正在为数据库系统的 GUI 开发 window。我试图在同一个 JFrame 中同时拥有 JScrollPane 和 JPanel。我基本上想要一个用户可以滚动浏览数据的部分,然后是底部不滚动的部分,那里有按钮可以更改排序。当前,当我尝试打开 window 时,仅显示 JPanel。我知道 JScrollPane 本身可以工作,因为如果我注释掉添加 JPanel 的部分,它就会正常工作。

public class ViewWindow
{
   DataContainer data;
   JFrame viewWin;
   DaysUntil days;
   JPanel contentPane;
   JScrollPane scroll;
   EmptyBorder border;
   DateFormat dateformat;
   Integer[] map;
   SortTest sor;
   JButton dayUntil, index, name;

   public ViewWindow(DataContainer da)
   {
       data= da;
       days= new DaysUntil();
       sor= new SortTest(data,days);
       viewWin= createWindow();
       JScrollPane main= createMainPanel();
       JPanel sortPane= createSortPanel();
       viewWin.getContentPane().add(main);
       viewWin.getContentPane().add(sortPane);
       viewWin.pack();
       viewWin.setVisible(false);

  }

这是 createMainPanel() 的部分代码

public JScrollPane createMainPanel()
   {
      DateFormat dateformat =new SimpleDateFormat("MM/dd/yy");
      border = new EmptyBorder(10,20,10,20);
      JPanel mainPane= new JPanel();
      mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));

      JPanel titlePane= new JPanel();
      titlePane.setLayout(new BoxLayout(titlePane, BoxLayout.Y_AXIS));

      contentPane= new JPanel();
      contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));

      JPanel indexPane= new JPanel();
         indexPane.setLayout(new BoxLayout(indexPane, BoxLayout.Y_AXIS));
         JLabel indexTitle= new JLabel("index");
         indexTitle.setBorder(border);
         indexPane.add(indexTitle);

       .....
       mainPane.add(titlePane);
  mainPane.add(contentPane);
  JScrollPane mainn= new JScrollPane(mainPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  return mainn;
 }

JPanel 如下:

public JPanel createSortPanel()
   {
      JPanel sortPanel = new JPanel();
      sortPanel.setLayout(new BoxLayout(sortPanel, BoxLayout.X_AXIS));

      dayUntil= new JButton("Sort by Due Date");
      index= new JButton("Sort by index");
      name= new JButton("Sort by name");
      sortPanel.add(dayUntil);
      sortPanel.add(index);
      sortPanel.add(name);
      return sortPanel;
   }

如果有人能提供帮助,我们将不胜感激。

JFame 的默认布局是支持此要求的 BorderLayout:

基本逻辑是:

frame.add(scrollPane, BorderLayout.CENTER)
frame.add(anotherPanel, BorderLayout.PAGE_END);

阅读 Swing 教程中有关 Layout Manager 的部分以获取工作示例,以更好地帮助您理解 BorderLayout 的工作原理。