Boa noite a todos!
Estou estudando um exemplo do Livro Java - Como programar, Deitel, 8ª edição (página 919), e estou confuso sobre os métodos GetColumnClass(), GetColumnCount(), GetColumnName(), GetRowCount() e GetValueAt().
Quando é que esses métodos são invocados??? E por quem??? E por que razão???
Neste ponto, o Deitel não é muito claro, somado também ao fato de eu ainda estou a aprender Java.
Por favor, alguém me ajude!!!
Seguem os códigos,
package bancodedados2;
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;
// keep track of database connection status
private boolean connectedToDatabase = false;
// constructor initializes resultSet and obtains its meta data object;
// determines number of rows
public ResultSetTableModel( String url, String username,
String password, String query ) throws SQLException
{
// connect to database
connection = DriverManager.getConnection( url, username, password );
// create Statement to query database
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
// update database connection status
connectedToDatabase = true;
// set query and execute it
setQuery( query );
}
// get class that represents column type
@Override
public Class getColumnClass( int column ) throws IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// determine Java class of column
try
{
String className = metaData.getColumnClassName( column + 1 );
// return Class object that represents className
return Class.forName( className );
}
catch ( Exception exception )
{
exception.printStackTrace();
}
return Object.class; // if problems occur above, assume type Object
}
// get number of columns in ResultSet
@Override
public int getColumnCount() throws IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// determine number of columns
try
{
return metaData.getColumnCount();
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
}
return 0; // if problems occur above, return 0 for number of columns
}
// get name of a particular column in ResultSet
@Override
public String getColumnName( int column ) throws IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// determine column name
try
{
return metaData.getColumnName( column + 1 );
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
}
return ""; // if problems, return empty string for column name
}
// return number of rows in ResultSet
@Override
public int getRowCount() throws IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
return numberOfRows;
}
// obtain value in particular row and column
@Override
public Object getValueAt( int row, int column )
throws IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// obtain a value at specified ResultSet row and column
try
{
resultSet.absolute( row + 1 );
return resultSet.getObject( column + 1 );
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
}
return ""; // if problems, return empty string object
}
// set new database query string
public void setQuery( String query )
throws SQLException, IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// specify query and execute it
resultSet = statement.executeQuery( query );
// obtain meta data for ResultSet
metaData = resultSet.getMetaData();
// determine number of rows in ResultSet
resultSet.last(); // move to last row
numberOfRows = resultSet.getRow(); // get row number
// notify JTable that model has changed
fireTableStructureChanged();
}
// close Statement and Connection
public void disconnectFromDatabase()
{
if ( connectedToDatabase )
{
// close Statement and Connection
try
{
resultSet.close();
statement.close();
connection.close();
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
}
finally // update database connection status
{
connectedToDatabase = false;
}
}
}
}
package bancodedados2;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.regex.PatternSyntaxException;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.TableRowSorter;
import javax.swing.table.TableModel;
public class DisplayQueryResults extends JFrame
{
// database URL, username and password
static final String DATABASE_URL = "jdbc:mysql://localhost/books";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// default query retrieves all data from authors table
static final String DEFAULT_QUERY = "SELECT * FROM authors";
private ResultSetTableModel tableModel;
private JTextArea queryArea;
// create ResultSetTableModel and GUI
public DisplayQueryResults()
{
super( "Displaying Query Results" );
// create ResultSetTableModel and display database table
try
{
// create TableModel for results of query SELECT * FROM authors
tableModel = new ResultSetTableModel( DATABASE_URL,
USERNAME, PASSWORD, DEFAULT_QUERY );
// set up JTextArea in which user types queries
queryArea = new JTextArea( "palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra palavra Sets the line-wrapping policy of the text area.", 3, 100 );
//queryArea = new JTextArea( DEFAULT_QUERY, 3, 100 );
queryArea.setWrapStyleWord( true );
queryArea.setLineWrap( true );
JScrollPane scrollPane = new JScrollPane( queryArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
// set up JButton for submitting queries
JButton submitButton = new JButton( "Submit Query" );
// create Box to manage placement of queryArea and
// submitButton in GUI
Box boxNorth = Box.createHorizontalBox();
boxNorth.add( scrollPane );
boxNorth.add( submitButton );
// create JTable based on the tableModel
JTable resultTable = new JTable( tableModel );
JLabel filterLabel = new JLabel( "Filter:" );
final JTextField filterText = new JTextField();
JButton filterButton = new JButton( "Apply Filter" );
Box boxSouth = Box.createHorizontalBox();
boxSouth.add( filterLabel );
boxSouth.add( filterText );
boxSouth.add( filterButton );
// place GUI components on content pane
add( boxNorth, BorderLayout.NORTH );
add( new JScrollPane( resultTable ), BorderLayout.CENTER );
add( boxSouth, BorderLayout.SOUTH );
// create event listener for submitButton
submitButton.addActionListener(
new ActionListener()
{
// pass query to table model
@Override
public void actionPerformed( ActionEvent event )
{
// perform a new query
try
{
tableModel.setQuery( queryArea.getText() );
}
catch ( SQLException sqlException )
{
JOptionPane.showMessageDialog( null,
sqlException.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
// try to recover from invalid user query
// by executing default query
try
{
tableModel.setQuery( DEFAULT_QUERY );
queryArea.setText( DEFAULT_QUERY );
}
catch ( SQLException sqlException2 )
{
JOptionPane.showMessageDialog( null,
sqlException2.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
// ensure database connection is closed
tableModel.disconnectFromDatabase();
System.exit( 1 ); // terminate application
}
}
}
}
);
final TableRowSorter< TableModel > sorter =
new TableRowSorter< TableModel >( tableModel );
resultTable.setRowSorter( sorter );
setSize( 500, 250 ); // set window size
setVisible( true ); // display window
// create listener for filterButton
filterButton.addActionListener(
new ActionListener()
{
// pass filter text to listener
@Override
public void actionPerformed( ActionEvent e )
{
String text = filterText.getText();
if ( text.length() == 0 )
sorter.setRowFilter( null );
else
{
try
{
sorter.setRowFilter(
RowFilter.regexFilter( text ) );
}
catch ( PatternSyntaxException pse )
{
JOptionPane.showMessageDialog( null,
"Bad regex pattern", "Bad regex pattern",
JOptionPane.ERROR_MESSAGE );
}
}
}
}
);
}
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
}
// dispose of window when user quits application (this overrides
// the default of HIDE_ON_CLOSE)
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
// ensure database connection is closed when user quits application
addWindowListener(
new WindowAdapter()
{
// disconnect from database and exit when window has closed
@Override
public void windowClosed( WindowEvent event )
{
tableModel.disconnectFromDatabase();
System.exit( 0 );
}
}
);
}
// execute application
public static void main( String args[] )
{
new DisplayQueryResults();
}
}