Current Position:Home > How to edit databases from JTable?

How to edit databases from JTable?

Update:10-11Source: network consolidation
Advertisement
Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
I have the installer of an application which I made with Java SE called FuelStation.exe
My class files are ready for sharing along with its source files.
I have placed it in this location in my website:
http://www.apachevista.com/alphaprojects/runfiles/
It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
Here is my sample code:
// DisplayQueryResults.java
// Display the contents of the Authors table in the
// Books database.
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 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.JInternalFrame;
import java.util.*; // for the Bundle
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.event.InternalFrameAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.*; // step 1
import javax.swing.table.TableModel; // step 1
public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
// JDBC driver, database URL, username and password
ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
final String JDBC_DRIVER = bundle.getString("Driver");
final String DATABASE_URL = bundle.getString("URL");
final String USERNAME = bundle.getString("User");
final String PASSWORD = bundle.getString("Password");
// default query retrieves all data from authors table
//static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
final String DEFAULT_QUERY = bundle.getString("Query");
private ResultSetTableModel tableModel;
private JTextArea queryArea;
static final int xOffset = 0, yOffset = 200;
private boolean ALLOW_COLUMN_SELECTION = false;
private boolean ALLOW_ROW_SELECTION = true;
// create ResultSetTableModel and GUI
public DisplayQueryResults() {  
super("Sales of the Day",
true, //resizable
true, //closable
true, //maximizable
false);//iconifiable
//...Create the GUI and put it in the window...
//Set the window's location.
setLocation(xOffset, yOffset);
// create ResultSetTableModel and display database table
try {
// create TableModel for results of query SELECT * FROM authors
tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
USERNAME, PASSWORD, DEFAULT_QUERY);
// set up JTextArea in which user types queries
queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
queryArea.setWrapStyleWord(true);
queryArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(queryArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// set up JButton for submitting queries
JButton submitButton = new JButton("Submit Query");
// create Box to manage placement of queryArea and
// submitButton in GUI
Box box = Box.createHorizontalBox();
box.add(scrollPane);
box.add(submitButton);
// create JTable delegate for tableModel
JTable resultTable = new JTable(tableModel);
resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
resultTable.setRowSelectionAllowed(true);
resultTable.getModel().addTableModelListener(this); // step 3
// place GUI components on content pane
add(box, BorderLayout.NORTH);
add(new JScrollPane(resultTable), BorderLayout.CENTER);
// create event listener for submitButton
submitButton.addActionListener(
new ActionListener()
// pass query to table model
public void actionPerformed(ActionEvent event)
// perform a new query
try
tableModel.setQuery(queryArea.getText());
} // end try
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);
} // end try
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
} // end inner catch
} // end outer catch
} // end actionPerformed
} // end ActionListener inner class
); // end call to addActionListener
//...Then set the window size or call pack...
     setSize(750,300);
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
// 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
addInternalFrameListener(
new InternalFrameAdapter() {
// 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
} // end DisplayQueryResults constructor
public void tableChanged(TableModelEvent e) { // step 4
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object tableModel = model.getValueAt(row, column);
// Do something with the data...
System.out.println(tableModel);
System.out.println("data");
// execute application
public static void main(String args[]) {
new DisplayQueryResults();
} // end main
} // end class DisplayQueryResults
My question is in lines 177-187:
public void tableChanged(TableModelEvent e) { // step 4
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object tableModel = model.getValueAt(row, column);
// Do something with the data...
System.out.println(tableModel);
System.out.println("data");
Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
PS:
When you have solved the problem, please notify me with the code that's changed
and please share it to others if you like so.
Best Wishes: Oliver Bob Lagumen
Email: [email protected]
website: www.apachevista.com
Oliver Bob Lagumen
Edited by: Oliverbob on Jan 24, 2008 9:03 PM

The Best Answer

Advertisement
Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?What does happen when you click on the cells?
Does the ResultSetTableModel report the cells as editable? If not you will never get to edit their contents, and so the table's model won't change, and so the table model listener will never get invoked.
When you post code here use the code tags. Basically you put {code} at the start of your code and again at the end. That way the code will be readable.
Try to post minimal examples with which others can reproduce your problem. In this case "minimal" would involve removing or drastically simplifying a lot of the GUI stuff which is just noise. But "reproduce" would involve including the ResultSetTableModel.
When you have solved the problem, please notify me with the code that's changedAvoid this.
What you say here is quite possibly not what you mean. But, in any event, while there might be plenty of interest in helping with specific problems there will likely be none in writing your code. Your problem remains yours. But your solution and your code - prompted by whatever help you might recieve - will also be yours.
  • How to edit databases from JTable? Update:10-11

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable. I have the installer of an application which I made with Java SE called FuelStatio

  • Update database from Jtable Update:11-30

    Hi all, I am trying to update database from Jtable. I added Jtable to scrollpane . My question is.. after updating the Jtable..I want to save the details to database..when I click save button on my screen...how to do that? Please help me out! Thanks

  • While generating a crystal report can we edit database fiels in field explorer (at middle can we edit database fields) Update:10-11

    while generating a crystal report can we edit database fiels in field explorer (at middle can we edit database fields)Wrong forum to post the question, try to post the question in crystal reports community. Its not possible to edit the database field

  • While generating a crystal report can we edit database files in field explorer ? Update:10-11

    Hi, while generating a crystal report can we edit database files in field explorer (at middle can we edit database fields) Regards, MahendraWrong forum to post the question, try to post the question in crystal reports community. Its not possible to e

  • Deployment of objects in OWB10g with Personal Edition Database Update:10-11

    When trying to deploy objects in a Personal Oracle 10g database with OWB10g, the following error occurs: RPE-01011: Cannot deploy to target database location because it does not have a compatible version. Deployment on the same database but on Enterp

  • How to extract data from dmp file to oracle express edition database Update:10-11

    Hi, I wanted to extract a oracle dump file in oracle express edition database. Is it possible? If yes, then can anyone please guide me how to do it? ThanksHi, This might help Backup/Export Question! Br,JariRead other 3 answers

  • Newly installed oracle 10g express edition database Update:10-11

    Hai to all I have fedora 15 operating system with oracle 10g express edition database installed .. I already have working knowledge in mysql database .. my question is that when i opened oracle database via sql developer , then by expanding tables ta

  • Using OBIEE with Oracle Express Edition Database? SOLVED Update:11-30

    I have a client that wants a quick demo of OBIEE. They sent us some csv files as the data source. I migrated them to Excel files for easier use, but the Excel files seem to have limitations on how I can combine the columns, such as concatenating and

  • How can I get oracle 9.2.0.7 Enterprise edition Database for Solaris? Update:11-30

    Hi, everybody, Reccently got involved in a project that require to setup Oracle 9.2.0.7 Enterprise edition Database for Solaris. However from oracle's download page, the only sun platform version for 9i is 9.2.0.1. so to get to 9.2.0.7, do i need to

  • How to Connect MySQL Database Through JTable? Update:11-30

    Hi, How to Connect MySQL Database Through JTable? anyone of u knows these concept please send me coding of that Part.. Thanks, Guru..Start by reading the tutorials. There's a section on Swing which shows you how to use tables and a section on JDBC wh