java 动态添加的 JTable 不显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/121715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically added JTable not displaying
提问by Graza
Java Newbie here. I have a JFrame that I added to my netbeans project, and I've added the following method to it, which creates a JTable. Problem is, for some reason when I call this method, the JTable isn't displayed. Any suggestions?
Java 新手在这里。我有一个 JFrame,已添加到我的 netbeans 项目中,并向其中添加了以下方法,该方法创建了一个 JTable。问题是,由于某种原因,当我调用此方法时,未显示 JTable。有什么建议?
public void showFromVectors(Vector colNames, Vector data) {
jt = new javax.swing.JTable(data, colNames);
sp = new javax.swing.JScrollPane(jt);
//NB: "this" refers to my class DBGridForm, which extends JFrame
this.add(sp,java.awt.BorderLayout.CENTER);
this.setSize(640,480);
}
The method is called in the following context:
该方法在以下上下文中被调用:
DBGridForm gf = new DBGridForm(); //DBGridForm extends JFrame
DBReader.outMatchesTable(gf);
gf.setVisible(true);
... where DBReader.outMatchesTable() is defined as
... 其中 DBReader.outMatchesTable() 定义为
static public void outMatchesTable(DBGridForm gf) {
DBReader ddb = new DBReader();
ddb.readMatchesTable(null);
gf.showFromVectors(ddb.lastRsltColNames, ddb.lastRsltData);
}
My guess is I'm overlooking something, either about the swing classes I'm using, or about Java. Any ideas?
我的猜测是我忽略了一些东西,要么是关于我正在使用的 Swing 类,要么是关于 Java。有任何想法吗?
采纳答案by davenpcj
"this" in your context is unclear. Is it inside an applet? a JFrame?
你的上下文中的“这个”不清楚。它在小程序内吗?一个 JFrame?
You may be having a layout issue, make sure you've called setLayout on your class with a new borderlayout.
您可能遇到布局问题,请确保您已使用新的边框布局在类上调用 setLayout。
In a swing application, you'd want to use getRootContentPane().add() instead of a raw add(), depending on the version.
在 Swing 应用程序中,您可能希望使用 getRootContentPane().add() 而不是原始 add(),具体取决于版本。
Java tutorial on adding top-level content: http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html
添加顶级内容的 Java 教程:http: //java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html
回答by Bill K
If you are not running on the event thread, it could be a problem--I've seen that cause stuff not to display.
如果您没有在事件线程上运行,则可能是一个问题——我已经看到导致内容不显示的情况。
If this code is called in response to an AWT event (mouse click, button press, ...) then that's not the problem, but if it's still the same thread that started your app, or this code is running off a timer, could very well be.
如果此代码是为响应 AWT 事件(鼠标单击、按钮按下等)而调用的,那么这不是问题,但如果它仍然是启动您的应用程序的同一个线程,或者此代码正在运行计时器,则可能很好。

