我有一个带有table,combobox的框架,我想通过combobox用数据库填充表格,但是如果我使用itemlistener我没有看到表格,没有itemlistener和String sql="select * from Arlista"
那么我看到我的数据表。
(combob =组合框)
编辑:现在我得到了main的错误,“修饰符'static'只允许在常量变量声明中
public static class TableFromDatabase extends JFrame
{ Vector columnNames = new Vector();
Vector data = new Vector();
String [] asd={"Arlista"};
JComboBox combob=new JComboBox(asd);
String tesztvalt2;
public TableFromDatabase() {
combob.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e){
tesztvalt2=(combob.getSelectedItem()).toString();
if (e.getItem().equals(tesztvalt2)) {
try {
String url="jdbc:sqlserver://FARKAS-PC;databaseName=Mozi;integratedSecurity=true;";
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName( driver );
Connection connection = DriverManager.getConnection( url );
String sql = "Select * from "+tesztvalt2+"";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
connection.close();
}
catch(Exception ex)
{
System.out.println( ex );
}
JTable table = new JTable(data, columnNames)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JPanel panel = (JPanel)getContentPane();
panel.add(buttonPanel, BorderLayout.SOUTH);
panel.revalidate();
panel.repaint();
}
}
public static void main(String[] args)
{
TableFromDatabase frame = new TableFromDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setVisible(true);
frame.pack();
}
});
}
}
答案 0 :(得分:1)
您从Table From Database复制的代码只是为了展示如何调用SQL并创建JTable并在框架可见之前将其添加到框架的基础知识。这意味着该代码中的pack()
方法将调用布局管理器,以便新创建的表具有有效大小。
您正尝试在可见的GUI上动态创建JTable。因此,您无法将表/滚动窗格添加到框架中。您还需要重新验证()所有组件。基本代码是:
JPanel panel = (JPanel)getContentPane();
panel.add(buttonPanel, BorderLayout.SOUTH);
panel.revalidate();
panel.repaint();