Segue o código:
Chamada do JDialog:
private void oM3ButtonSearch1ActionPerformed(java.awt.event.ActionEvent evt) {
DisplayQueryResults newUser_pl = new DisplayQueryResults(this, true);
newUser_pl.setVisible(true);
}
private void oM3ButtonSearch1ActionPerformed(java.awt.event.ActionEvent evt) {
DisplayQueryResults newUser_pl = new DisplayQueryResults(this, true);
newUser_pl.setVisible(true);
}
Rotinas da JDialog
package m3.promptlist;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class DisplayQueryResults extends javax.swing.JDialog {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/m3tef";
static final String USERNAME= "root";
static final String PASSWORD= "111";
static final String DEFAULT_QUERY = "SELECT NameUser, Name FROM m3sysuser";
private ResultSetTableModel tableModel;
public DisplayQueryResults(java.awt.Frame parent, boolean modal) {
super(parent, modal);
try
{
// create TableModel for results of query SELECT * FROM authors
tableModel = new ResultSetTableModel( JDBC_DRIVER, DATABASE_URL,
USERNAME, PASSWORD, DEFAULT_QUERY );
// create JTable delegate for tableModel
jTable1 = new JTable( tableModel );
// place GUI components on content pane
add( new JScrollPane( jTable1 ), BorderLayout.CENTER );
setSize( 500, 250 ); // set window size
setVisible( true ); // display window
} // end try
catch ( ClassNotFoundException classNotFound )
{
JOptionPane.showMessageDialog( null, "MySQL driver not found", "Driver not found", JOptionPane.ERROR_MESSAGE );
System.exit( 1 ); // terminate application
} // end catch
catch ( SQLException sqlException )
{
JOptionPane.showMessageDialog( null, sqlException.getMessage(), "Database error", JOptionPane.ERROR_MESSAGE );
// ensure database connection is closed
tableModel.disconnectFromDatabase();
System.exit( 1 ); // terminate application
} // end catch
setDefaultCloseOperation( DISPOSE_ON_CLOSE ); --
addWindowListener(new WindowAdapter()
{
// disconnect from database and exit when window has closed
public void windowClosed( WindowEvent event )
{
tableModel.disconnectFromDatabase();
System.exit( 0 );
} // end method windowClosed
} // end WindowAdapter inner class
); // end call to addWindowListener
}
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 [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
*/
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(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DisplayQueryResults dialog = new DisplayQueryResults(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
Rotinas da ResultSetTableModel
package m3.promptlist;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class DisplayQueryResults extends javax.swing.JDialog {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/m3tef";
static final String USERNAME= "root";
static final String PASSWORD= "111";
static final String DEFAULT_QUERY = "SELECT NameUser, Name FROM m3sysuser";
private ResultSetTableModel tableModel;
public DisplayQueryResults(java.awt.Frame parent, boolean modal) {
super(parent, modal);
try
{
// create TableModel for results of query SELECT * FROM authors
tableModel = new ResultSetTableModel( JDBC_DRIVER, DATABASE_URL,
USERNAME, PASSWORD, DEFAULT_QUERY );
// create JTable delegate for tableModel
jTable1 = new JTable( tableModel );
// place GUI components on content pane
add( new JScrollPane( jTable1 ), BorderLayout.CENTER );
setSize( 500, 250 ); // set window size
setVisible( true ); // display window
} // end try
catch ( ClassNotFoundException classNotFound )
{
JOptionPane.showMessageDialog( null, "MySQL driver not found", "Driver not found", JOptionPane.ERROR_MESSAGE );
System.exit( 1 ); // terminate application
} // end catch
catch ( SQLException sqlException )
{
JOptionPane.showMessageDialog( null, sqlException.getMessage(), "Database error", JOptionPane.ERROR_MESSAGE );
// ensure database connection is closed
tableModel.disconnectFromDatabase();
System.exit( 1 ); // terminate application
} // end catch
setDefaultCloseOperation( DISPOSE_ON_CLOSE ); --
addWindowListener(new WindowAdapter()
{
// disconnect from database and exit when window has closed
public void windowClosed( WindowEvent event )
{
tableModel.disconnectFromDatabase();
System.exit( 0 );
} // end method windowClosed
} // end WindowAdapter inner class
); // end call to addWindowListener
}
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 [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url]
*/
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(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DisplayQueryResults.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DisplayQueryResults dialog = new DisplayQueryResults(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
Rotinas da ResultSetTableModel
package m3.promptlist;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
public class ResultSetTableModel extends AbstractTableModel
{
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData metaData;
private int numberOfRows;
private boolean connectedToDatabase = false;
public ResultSetTableModel( String driver, String url,
String username, String password, String query )
throws SQLException, ClassNotFoundException
{
Class.forName( driver );
connection = DriverManager.getConnection( url, username, password );
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
connectedToDatabase = true;
setQuery( query );
} // end constructor ResultSetTableModel
@Override
public Class getColumnClass( int column ) throws IllegalStateException
{
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
try
{
String className = metaData.getColumnClassName( column + 1 );
return Class.forName( className );
} // end try
catch ( Exception exception )
{
exception.printStackTrace();
} // end catch
return Object.class; // if problems occur above, assume type Object
} // end method getColumnClass
@Override
public int getColumnCount() throws IllegalStateException
{
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
try
{
return metaData.getColumnCount();
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
return 0; // if problems occur above, return 0 for number of columns
} // end method getColumnCount
@Override
public String getColumnName( int column ) throws IllegalStateException
{
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
try
{
return metaData.getColumnName( column + 1 );
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
return ""; // if problems, return empty string for column name
} // end method getColumnName
@Override
public int getRowCount() throws IllegalStateException
{
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
return numberOfRows;
} // end method getRowCount
@Override
public Object getValueAt( int row, int column )
throws IllegalStateException
{
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
try
{
resultSet.absolute( row + 1 );
return resultSet.getObject( column + 1 );
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
return ""; // if problems, return empty string object
} // end method getValueAt
public void setQuery( String query )
throws SQLException, IllegalStateException
{
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
resultSet = statement.executeQuery( query );
metaData = resultSet.getMetaData();
resultSet.last(); // move to last row
numberOfRows = resultSet.getRow(); // get row number
fireTableStructureChanged();
} // end method setQuery
public void disconnectFromDatabase()
{
if ( !connectedToDatabase )
return;
try
{
statement.close();
connection.close();
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
finally // update database connection status
{
connectedToDatabase = false;
} // end finally
} // end method disconnectFromDatabase
} // end class ResultSetTableModel