public class MyDataBase extends JPanel
{
String sql;
//String tablename;
public MyDataBase(){}
public MyDataBase(String sql)
{
System.out.printf("hai");
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
// this.tablename=tablename;
this.sql =sql;
// This will ensure that the sql objects are closed when the program
// is finished with them
try {
Connection con=DatabaseConnection.getConnection();
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
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;
}
};
JFrame frame=new JFrame();
JScrollPane scrollPane = new JScrollPane( table );
frame.getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
frame.getContentPane().add( buttonPanel, BorderLayout.SOUTH );
System.out.println("Query Building"+sql);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
String tablename = in.nextLine();
System.out.println("You entered : " + tablename);
String sql=" SELECT * FROM "+tablename;
JFrame frame = new JFrame();
MyDataBase pan = new MyDataBase(sql);
pan.setVisible(true);
frame.add(pan);
frame.pack();
frame.setVisible(true);
System.out.println("hai");
}
}
仅显示帧的输出,而不是表数据。
答案 0 :(得分:1)
您创建了JFrame
两次。 main()
中的{{}}和MyDataBase(String sql)
中的第二个,您可以在其中添加表格和滚动窗格。您需要将滚动窗格添加到main()
中创建的框架中。 (或者,由于MyDataBase
扩展了JPanel
,因此将MyDataBase
添加到main()
中的框架应按预期工作)
此外,swing是单线程的,您应该只在事件派发线程中创建和访问swing组件。请参阅tutorial,其中详细说明了如何执行此操作。