简体   繁体   English

使用JScrollPane时Java Swing JTable不显示滚动条

[英]Java swing JTable doesn't show scroll bar when using JScrollPane

I have a tablePanel which is a JScrollPane ,and initialized with a JTable , the JTable initialized with a defaultTableModel .When I trying to add some rows to the table, but didn't see the scroll bar, appriciated for any reply. 我有一个tablePanel ,它是一个JScrollPane ,并使用JTable了初始化,而JTable使用了defaultTableModel进行了初始化。当我尝试向表中添加一些行,但没有看到滚动条时,希望得到任何答复。

JFrame jFrame = new JFrame();

//rows will be added dynamically.
DefaultTableModel defautTableModel = new DefaultTableModel(null,columnNames){
  @Override
  public boolean isCellEditable(int row, int column) {
    return false;
  }
};

JTable jTable = new JTable(defautTableModel);
jTable.setLocation(20,60);
jTable.setSize(950,450);
jTable.setRowHeight(25);

jTable.getColumn("No.").setMaxWidth(45);
jTable.getColumn("position").setMaxWidth(45);
...

JTableHeader jTableHeader = jTable.getTableHeader();
jTableHeader.setLocation(20,30);
jTableHeader.setSize(950,30);
jTableHeader.setFont(new Font(null, Font.BOLD, 16));
jTableHeader.setResizingAllowed(true);
jTableHeader.setReorderingAllowed(true);

JScrollPane tablePanel = new JScrollPane(jTable);
tablePanel.setLayout(null);
tablePanel.add(jTableHeader);
tablePanel.add(jTable);

jFrame.setContentPane(tablePanel);

tablePanel.setLayout(null); is the primary cause of your problem. 是您问题的主要原因。 A JScrollPane has its own layout manager which is used to manage the scrollbars, view port and headers. JScrollPane有其自己的布局管理器,该管理器用于管理滚动条,查看端口和标题。

tablePanel.add is your next problem, as you shouldn't be adding components to the JScrollPane . tablePanel.add是您的下一个问题,因为您不应该向JScrollPane添加组件。 Instead, you should be setting the JScrollPane 's JViewPort . 相反,您应该设置JScrollPaneJViewPort

But, since you're using JScrollPane tablePanel = new JScrollPane(jTable); 但是,由于您使用的是JScrollPane tablePanel = new JScrollPane(jTable); , there's actually no need for the three lines which follow it. ,实际上不需要紧随其后的三行。

I would highly recommend that you take a closer look at: 我强烈建议您仔细看一下:

Now, before you tell me how nothing I've suggested actually works, go and re-read Laying Out Components Within a Container - this is the corner stone concept you will need to understand and master before Swing really begins to work for you 现在,在您告诉我我建议的内容实际上没有任何作用之前,请重新阅读在容器中放置组件的知识 -这是您在Swing真正开始为您工作之前需要了解和掌握的基本概念

JScrollPane tablePanel = new JScrollPane(jTable);

// No need for the below code

/*tablePanel.setLayout(null);

tablePanel.add(jTableHeader);

tablePanel.add(jTable);*/

jFrame.setContentPane(tablePanel);

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

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