关于jtable不能显示表头的问题?

importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importjava.util.*;publicc... import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class PurchaseModule {

public PurchaseModule() {

JFrame f = new JFrame();

Object[][] playerInfo = {
{"阿呆", new Integer(66),
new Integer(32), new Integer(98), new Boolean(false),new Boolean(false)},
{"阿瓜", new Integer(85),
new Integer(69), new Integer(154), new Boolean(true),new Boolean(false)},
};

String[] Names = {"姓名",
"语文",
"数学",
"总分",
"及格",
"作弊"};

JTable table = new JTable(playerInfo, Names);
table.setPreferredScrollableViewportSize(new Dimension(550, 30));

JScrollPane scrollPane = new JScrollPane(table);

f.getContentPane().add(scrollPane,BorderLayout.CENTER);
//f.getContentPane().add(table,BorderLayout.CENTER);,问为什么把上面的这句改成这样就不能显示表头啊?

f.setTitle("Simple Table");
f.pack();
f.setVisible(true);

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

}

public static void main(String args[]) {

PurchaseModule b = new PurchaseModule();
}
}
展开
 我来答
zkenshin
推荐于2016-06-04 · TA获得超过294个赞
知道答主
回答量:306
采纳率:0%
帮助的人:222万
展开全部
JTable组件显示数据时,如果直接将其放置在Frame的contentPane中则表头一行会显示不出来,如果将其放置在JScrollPane中显示数据的话,表头会自动显示出来。

引用Sun的原话为:

It's easy to put a table in a scroll pane. You need just one or two lines of code:
JScrollPane scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
The scroll pane automatically gets the table's header, which displays the column names, and puts it on top of the table. Even when the user scrolls down, the column names remain visible at the top of the viewing area. The scroll pane also tries to make its viewing area the same as the table's preferred viewing size. The previous code snippet sets the table's preferred viewing size with the setPreferredScrollableViewportSize method.
If you're using a table without a scroll pane, then you must get the table header component and place it yourself. For example:

container.setLayout(new BorderLayout());
container.add(table.getTableHeader(), BorderLayout.PAGE_START);
container.add(table, BorderLayout.CENTER);在使用时要注意!

参考资料: http://blog.csdn.net/sting2005/archive/2007/03/13/1527953.aspx

本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式