Why is my table not visible when it's in a JScrollPane?

南笙酒味 提交于 2019-11-29 16:05:16

This is your problem:

scrollPane.add(table);

This does not add the JTable to the JScrollPane's viewport's view which is where you want it, but rather completely replaces the JScrollPane's viewport with the JTable, making the JScrollPane completely nonfunctional. Instead set the table as the JScrollPane's viewportview:

scrollPane.setViewportView(table);

Do either this or pass the table into the JScrollPane's constructor which does pretty much the same thing:

JScrollPane scrollPane = new JScrollPane(table,
          ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
          ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

This is all well explained in the JScrollPane API, and you will want to give it a look for the important details.


Edit
Your code also calls setVisible(true) on the JFrame before adding all components which can lead to trouble. You'll want to avoid doing this.

Try any one

scrollPane = new JScrollPane(table);

or

scrollPane = new JScrollPane(table,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

or

scrollPane.getViewport().add(table);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!