请帮助将结果集放入gui jtable!如果我自己从代码中执行 Jtable - 一切都很好<但是如果我使用 Netbeans 来处理它,我会遇到错误。
在代码中我做了 2 个表,但我不能把他们的数据源放到 myTable 中。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package db;
/**
*
* @author ma.matveev
*/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import javax.swing.table.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class Table extends javax.swing.JFrame {
//Connection conn = null;
//ResultSet rs = null;
// PreparedStatement pst = null;
/**
* Creates new form Table
*/
public Table() throws ClassNotFoundException {
try {
// Connect_db.ConnectDb("root","root");
Update_table ();
tableOutput() ;
} catch (SQLException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
initComponents();
}
public void tableOutput() throws SQLException, ClassNotFoundException {
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@//10.123.3.6:1521/rootdb", "root" , "root");
//Statement statement = conn.createStatement();
// ResultSet rs=statement.executeQuery("select * from V$Version v ");
// ResultSetMetaData rsmetadata = rs.getMetaData();
Statement ps = conn.createStatement();
ResultSet rs = ps.executeQuery("select * from V$Version v ");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
Vector data = new Vector(columnCount);
Vector row = new Vector(columnCount);
Vector columnNames = new Vector(columnCount);
columnNames.add("1");
columnNames.add("2");
columnNames.add("3");
columnNames.add("4");
columnNames.add("5");
columnNames.add("6");
columnNames.add("7");
columnNames.add("8");
columnNames.add("9");
columnNames.add("10");
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
row = new Vector(columnCount); // Create a new row Vector
}
TableModel tm = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
////jTableSchedule.setModel(tm);
//jTableSchedule.setFont(new Font("Tahoma", Font.PLAIN, 12));
myTable.setModel(tm);
}
private void Update_table () throws SQLException {
try {
Class.forName ("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@//10.123.3.6:1521/rootdb", "root" , "root");
Statement statement = conn.createStatement();
ResultSet rs=statement.executeQuery("select * from V$Version v ");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name = new Vector();
Vector data_rows = new Vector();
//System.out.println(columns);
for (int i=1; i<=columns; i++){
// System.out.println(i);
columns_name.addElement(rsmetadata.getColumnName(i));
}
// System.out.println(columns_name);
dtm.setColumnIdentifiers(columns_name);
while (rs.next()) {
// System.out.println(rs.getObject(1));
data_rows = new Vector();
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
//System.out.println("123");
//System.out.println(rs.getString(j));
}
//System.out.println(rs.getObject(1));
//System.out.println(data_rows.isEmpty());
//System.out.println(rs.getObject(1));
dtm.addRow(data_rows);
//data.addElement(data_rows);
// System.out.println(data.lastElement());
}
JTable table = new JTable(dtm);
// JTable myTable = new JTable(dtm);
JOptionPane.showMessageDialog(null, new JScrollPane(table));
//JOptionPane.showMessageDialog(null, new JScrollPane(myTable));
//System.out.println(dtm.getColumnName(0));
String[][] data = new String[1][4];
data[0][0]="1";
data[0][1]="1";
data[0][2]="1";
data[0][3]="1";
String[] columnNames = new String[]{
"IP", "PC_NAME", "ttl", "db"
};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table1 = new JTable(model);
// JTable myTable = new JTable(dtm);
JOptionPane.showMessageDialog(null, new JScrollPane(table1));
// myTable.setModel(dtm);
//myTable.setModel(DbUtils.resultSetToTableModel(rs));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
myTable = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
myTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(myTable);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(15, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new Table().setVisible(true);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTable myTable;
// End of variables declaration
}
如果我想放入 gui 的 myTable 会出错
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at db.Table.tableOutput(Table.java:89)
at db.Table.<init>(Table.java:35)
at db.Table$2.run(Table.java:246)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
ПОСТРОЕНИЕ УСПЕШНО ЗАВЕРШЕНО (общее время: 10 секунд)