Jtable database
Hi
I have a Jtable running in applet and I want this JTable to get its data from the database. how can I do that? use rmi or there is an easier way?
Thanks
Benbak
hi
this may help you
http://freewebs.com/tareitas/jtable.html
Similar Messages
-
Dear All...
I'm using a JTable to make changes (Update, Insert, Delete) On/To/From a database table....
I use HSQLDB Database engine (exactly OOo Base Database)...
I let the user to add multiple row, edit cells, and when he finishes his work, he simply click on Save button or Click on Cancel button
when he clicked the Save button the changes (inserted rows, and updated rows) should be done inside the database table...
when he clicked the cancel button nothing will happen...
should the program on clicking the Save button, iterate all rows from the JTable and update them (if the row exists) or insert them (if the row is not exists)
or there are another way (faster) that only write the changes (inserted, updated)????
can any body help me?It's up to you. If there's only 10 rows in the table, you might just want to completely refresh the table when the Save button is clicked. Or you might want to keep a flag for each row which keeps track of whether it has been changed or not.
-
Error in updating Jtable Database
package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
Error setting value at row 1 column 0 with value soup2
java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
at desktopapplication1.Datab.setValueAt(Datab.java:104)
at javax.swing.JTable.setValueAt(JTable.java:2719)
at javax.swing.JTable.editingStopped(JTable.java:4721)
at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
at javax.swing.JTextField.postActionEvent(JTextField.java:705)
at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
at java.awt.Component.processEvent(Component.java:6040)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
at java.awt.Component.dispatchEventImpl(Component.java:4502)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
my db is like
RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
soup 3 2 11 fish
chocolate 3 2 44 dessert
Edited by: kainard on Aug 1, 2010 2:31 PM
Edited by: kainard on Aug 1, 2010 2:37 PMCan you explain why you declare
private Connection conn;
private Statement st;
private ResultSet rs;
private ResultSetMetaData rsmd;
as private -
Refresh jTable after inserting new data into the Database
Hey all,
I'm using Netbeans 6.5 to create a Desktop Application which is connected to a Java DB (Derby).
The first simple steps were all very successfull:
Create the jTable and bind it to the Database => everything works fine. When the application starts it correctly shows all data from the database.
The problem starts when I try to insert new data to the database.
For that reason I've created textfields and a button "Save". When I press the button it successfully inserts the data to the database but they are not displayed in the jTable (when the application starts they are all there, they are not updated at runtime) . I've tried table.invalidate() and table.repaint() but they just don't work.
Any help will be GREATLY appreciated. But please have in mind that most of the code is Netbeans-generated and most of it not editable.
Many thanks in advance.
GeorgeOnce again you are right my friend. I jumped to conclusion way too fast, when I shouldn't. (Give me a break, I've been busting my head with this well over a week). The response I saw when I did that was that indeed a line is added to the jTable. Because I falsly set the index of the object to be added to be second to last the row appeared on the table, what I didn't see at the time was that the last one disappeared. Hmm...
A new adventure begins...
So after a few hours of messing around with it here are my observations:
1) It was not an observable list. When I add the new element with employeesList.add(newEmp); , the table gets notified but a get a bunch of exceptions:
xception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 84, Size: 84
at java.util.ArrayList.RangeCheck(ArrayList.java:546)
at java.util.ArrayList.get(ArrayList.java:321)
at org.jdesktop.swingbinding.impl.ListBindingManager$ColumnDescriptionManager.validateBinding(ListBindingManager.java:191)
at org.jdesktop.swingbinding.impl.ListBindingManager.valueAt(ListBindingManager.java:99)
at org.jdesktop.swingbinding.JTableBinding$BindingTableModel.getValueAt(JTableBinding.java:713)
at javax.swing.JTable.getValueAt(JTable.java:1903)
at javax.swing.JTable.prepareRenderer(JTable.java:3911)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1974)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1897)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:154)
at javax.swing.JComponent.paintComponent(JComponent.java:743)
at javax.swing.JComponent.paint(JComponent.java:1006)
at javax.swing.JViewport.blitDoubleBuffered(JViewport.java:1602)
at javax.swing.JViewport.windowBlitPaint(JViewport.java:1568)
at javax.swing.JViewport.setViewPosition(JViewport.java:1098)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.vsbStateChanged(BasicScrollPaneUI.java:818)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(BasicScrollPaneUI.java:807)
at javax.swing.DefaultBoundedRangeModel.fireStateChanged(DefaultBoundedRangeModel.java:348)
at javax.swing.DefaultBoundedRangeModel.setRangeProperties(DefaultBoundedRangeModel.java:285)
at javax.swing.DefaultBoundedRangeModel.setValue(DefaultBoundedRangeModel.java:151)
at javax.swing.JScrollBar.setValue(JScrollBar.java:441)
at javax.swing.plaf.basic.BasicScrollBarUI.scrollByUnits(BasicScrollBarUI.java:907)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.mouseWheelMoved(BasicScrollPaneUI.java:778)
at javax.swing.plaf.basic.BasicScrollPaneUI$MouseWheelHandler.mouseWheelMoved(BasicScrollPaneUI.java:449)
at apple.laf.CUIAquaScrollPane$XYMouseWheelHandler.mouseWheelMoved(CUIAquaScrollPane.java:38)
at java.awt.Component.processMouseWheelEvent(Component.java:5690)
at java.awt.Component.processEvent(Component.java:5374)
at java.awt.Container.processEvent(Container.java:2010)
at java.awt.Component.dispatchEventImpl(Component.java:4068)
at java.awt.Container.dispatchEventImpl(Container.java:2068)
at java.awt.Component.dispatchMouseWheelToAncestor(Component.java:4211)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Container.dispatchEventImpl(Container.java:2068)
at java.awt.Component.dispatchEvent(Component.java:3903)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
at java.awt.Container.dispatchEventImpl(Container.java:2054)
at java.awt.Window.dispatchEventImpl(Window.java:1801)
at java.awt.Component.dispatchEvent(Component.java:3903)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 84, Size: 84
at java.util.ArrayList.RangeCheck(ArrayList.java:546)
at java.util.ArrayList.get(ArrayList.java:321)
at org.jdesktop.swingbinding.impl.ListBindingManager$ColumnDescriptionManager.validateBinding(ListBindingManager.java:191)
at org.jdesktop.swingbinding.impl.ListBindingManager.valueAt(ListBindingManager.java:99)
at org.jdesktop.swingbinding.JTableBinding$BindingTableModel.getValueAt(JTableBinding.java:713)
at javax.swing.JTable.getValueAt(JTable.java:1903)
at javax.swing.JTable.prepareRenderer(JTable.java:3911)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
... and a lot morewhich from my poor understanding means that the jTable succesfully notices the change but it is not able (??) to adjust to the new change. What is more interesting is that when I plainly add the element to the end of the list (without an idex that is), a blank row appears at the end of my Table. The weird thing is that I've bound the table to some text fields below it, and when I select that empty row all the data appear correctly to the text fields.
I tried going through:
org.jdesktop.observablecollections.ObservableCollections.observableList(employeesList).add(newEmp);as well as
help = org.jdesktop.observablecollections.ObservableCollections.observableListHelper(employeesList);
help.getObservableList().add(newEmp);
help.fireElementChanged(employeesList.lastIndexOf(newEmp));and
obsemployeesList = org.jdesktop.observablecollections.ObservableCollections.observableList(employeesList);
obsemployeesList.add(newEmp);and I still get the same results (both the exeptions and the mysterious empty row at the end of the table
So, I'm again in terrible need of your advice. I can't thank you enough for the effort you put into this.
Best regards,
George
Edited by: tougeo on May 30, 2009 11:06 AM
Edited by: tougeo on May 30, 2009 11:21 AM
Edited by: tougeo on May 30, 2009 11:30 AM -
To get the unique id of the selected row in a JTable as in Database
Hi,
After fetching the recodrs from the Database, I have displayed them in a JTable. Though I fetched all the columns from db, I am displying only only 2 columns, say Name and Number neither of which is unique, however I have a unique ID for each record in the db. Now when I select some row in the JTable, I need to know its unique ID (the one which is in the db) which i have not displayed in the JTable.
Is there any API method that can store the unique ids of a table? Or how can this be done?
Thanks in Advance.Although, if you don't want the Id visible in the table, then you need to remove its TableColumn from the TableColumnModel.
Then when you want to reference the id you need to use:
table.getModel.getValueAt(...); -
Hi!
I have a ResultSet from a database query (select * from table) and I plan to turn it into a Object[][] in order to satisfy one of the DefaultTableModel's constructor ("DefaultTableModel(Object[][] data, Object[] columnNames)") and place it in a JTable - how do I go about in doing this.
I tried this:
myJTable.setModel(new DefaultTableModel(getData(rs),columnNames));
private Object getData(ResultSet rs){
java.util.ArrayList<Object[]> mySets = new java.util.ArrayList<Object[]>();
try{
while(rs.next()){
Object[] row = {
rs.getString("column1"), rs.getString("column2"), new Boolean(false)
ResultSets.add(row);
catch(Exception e){
e.printStackTrace();
return mySets;
But got this error when I compiled:
cannot find symbol
symbol : constructor DefaultTableModel(java.lang.Object,java.lang.String[])
location: class javax.swing.table.DefaultTableModel
new DefaultTableModel(
1 error
BUILD FAILED (total time: 0 seconds)
I'm trying to do this because I would want to have my JTable to have a checkbox in it like what's shown in the Java tutorial's SimpleTableDemo.java.
Basically, am getting data directly from the database - those that are set to 1 is enabled and 0 to disabled, then represent those as check boxes in the JTable.
Thank you so much for your help!Thanks calvino_ind!
I've managed to get your suggestion to work:
while(rs.next()){
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
obj[i][j] = rs.getObject(j+1);
rs.next();
}Issues:
I had to define the number of rows in order to initialize the Object's size:
Object[][] obj = new Object[number of rows][number of columns];*column size can be retrieved from what's shown in previous post.
To get the number of rows I had to do this:
while(rs.next()){ row++; }But in doing so, the cursor moves to the last row of the ResultSet. To move it back I had to execute this:
rs.beforeFirst();Here's the whole section of the code that's been my concern:
private Object[][] getData(ResultSet rs){
Object[][] obj = null;
int row = 0;
int col = 0;
ResultSetMetaData rsmd;
try{
rsmd = rs.getMetaData();
while(rs.next()){ row++; }
System.out.println(rs.getFetchSize());
col = rsmd.getColumnCount();
obj = new Object[row][col];
rs.beforeFirst();
while(rs.next()){
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
obj[i][j] = rs.getObject(j+1);
rs.next();
}catch(Exception e){
e.printStackTrace();
return obj;
}Now I did a little bit of fiddling around the forums, and came across a discussion that's it's not advisable to get the row count (second post of this link: http://forum.java.sun.com/thread.jspa?threadID=683676&messageID=3982010).
Anyone care to shed some more light into this?
Thanks! -
How do i add data from database to JTable ! Urgent
How do i add data from database to the columns of JTable?.
hi,
Thanks for ur link. but this is just a part of my application which i am developing user interface in swing package for which i want to know how to show data to user in the table format where by table input data will be from the database. say something like todays activity is shown to the user in table format... So u have any idea of how to do this... -
Cannot get text file to print in jtable. Using text file as a database
Instead of doing JDBC i am using text file as database. I cant get data from text file to print into JTable when i click find button. Goal is to find a record and print that record only, but for now i am trying to print all the records. Once i get that i will change my code to search desired record and print it. when i click the find button nothing happens. Can you please take a look at my code, dbTest() method. thanks.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
public class GUIdirectory extends JFrame
implements ActionListener {
// Define the components and the layout
JLabel inputLabel_lastname = new JLabel("Last Name");
JTextField inputText_lastname = new JTextField("Last Name",15);
JLabel inputLabel_firstname = new JLabel("First Name");
JTextField inputText_firstname = new JTextField(" ",15);
JLabel inputLabel_middleinitial = new JLabel("Middle Initial");
JTextField inputText_middleinitial = new JTextField(" ",4);
JButton inputButton = new JButton("Find");
JPanel inputLayout = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
JButton jButton1 = new JButton();
//create a new table and scrollpane
JTable dataTable = new JTable();
JScrollPane dataTableScrollPane = new JScrollPane();
public static void main(String args[]) {
GUIdirectory gui = new GUIdirectory("Telephone Directory");
gui.show();
gui.pack();
//TokenTest tt = new TokenTest();
//gui.dbTest();
public GUIdirectory(String Title) {
super(Title);
// Add ourselves as a listener for the window closing
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
exitWindow(1); }
inputLabel_lastname.setLabelFor(inputText_lastname);
inputText_lastname.setHorizontalAlignment(JTextField.RIGHT);
inputText_lastname.addActionListener(this);
inputLabel_firstname.setLabelFor(inputText_firstname);
inputText_firstname.setHorizontalAlignment(JTextField.RIGHT);
inputText_firstname.addActionListener(this);
inputLabel_middleinitial.setLabelFor(inputText_middleinitial);
inputText_middleinitial.setHorizontalAlignment(JTextField.RIGHT);
inputText_middleinitial.addActionListener(this);
inputButton.addActionListener(this);
inputLayout.add(inputLabel_lastname);
inputLayout.add(inputText_lastname);
inputLayout.add(inputLabel_firstname);
inputLayout.add(inputText_firstname);
inputLayout.add(inputLabel_middleinitial);
inputLayout.add(inputText_middleinitial);
inputLayout.add(inputButton);
getContentPane().setLayout(new BorderLayout(5,5));
getContentPane().add("North",inputLayout);
dataTableScrollPane.setViewportView(dataTable);
getContentPane().add("Center",dataTableScrollPane);
// A default method, primarily used for testing.
public void actionPerformed(ActionEvent evt) {
GUIdirectory gui = new GUIdirectory();
gui.dbTest();
void dbTest() {
DataInputStream dis = null;
String dbRecord = null;
String hold;
try {
File f = new File("customer.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
Vector dataVector = new Vector();
Vector headVector = new Vector(2);
Vector row = new Vector();
// read the record of the text database
while ( (dbRecord = dis.readLine()) != null) {
StringTokenizer st = new StringTokenizer(dbRecord, ",");
while (st.hasMoreTokens()) {
row.addElement(st.nextToken());
System.out.println("Inside nested loop: " + row);
System.out.println("inside loop: " + row);
dataVector.addElement(row);
System.out.println("outside loop: " + row);
headVector.addElement("Title");
headVector.addElement("Type");
dataTable = new JTable(dataVector, headVector);
dataTableScrollPane.setViewportView(dataTable);
} catch (IOException e) {
// catch io errors from FileInputStream or readLine()
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dis != null) {
try {
dis.close();
} catch (IOException ioe) {
} // end if
} // end finally
} // end dbTest
// Exits the program upon closing the window
public void exitWindow(int i) {
System.exit(i);
public GUIdirectory() {
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
private void jbInit() throws Exception {
jButton1.setText("jButton1");
this.getContentPane().add(jButton1, BorderLayout.CENTER);Nothing happens because in the actionPerformed() method you are creating a new version of GUIdirectory. You just want to execute the dbTest() method of the current instance of GUIdirectory.
The code should be:
public void actionPerformed(ActionEvent evt)
//GUIdirectory gui = new GUIdirectory();
//gui.dbTest();
dbTest(); -
How to edit databases from JTable?
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 PMWhy 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 put data in JTable from database
hi everyone,
i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
thank you
dhingIn [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.
-
JTable will not refresh with new data from database
Hi,
I have a JTable that does not recoginzed when the data has changed. The table is dynmaically populated with data from the database using a table model.
Please help!!
public JTable getUpdateContractTable() {
QueryTableModel model;
String [] dlrs = getSelectedDealers();
String [] stats = getSelectedStatuses();
String sql = buildContractQuery(dlrs, stats);
try {
if(isContractSet) {
model = new QueryTableModel();
model.setQuery(sql);
table.setModel(model);
table.setColumnModel(new UpdtCtrctColumnModel());
table.invalidate();
table.repaint();
//model.fireTableChanged(new TableModelEvent(model));
else {
model = new QueryTableModel();
UpdtCtrctColumnModel column = new UpdtCtrctColumnModel();
model.setQuery(sql);
table = new JTable(model, column);
table.createDefaultColumnsFromModel();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
model.fireTableChanged(null);
isContractSet = true;
catch (Exception e) {
System.out.println(e.getMessage());
//JOptionPane.show
//.showMessageDialog("Error: " + e.getMessage(),
// "Click Ok",
// JOptionPane.INFORMATION_MESSAGE);
return table;
}thank you for your help. i finally got it to refresh. i have a follow-up question if you don't mind answering it. i have 2 jtables where one depends on the other. when i do a refresh i want the other table to disappear, so i call the getContentPane().remove(component), but the table doesn't disappear. what should i do.
anthony -
Help with displaying dataBase onto JTable
hi
i've got this code(below ) ,but i don't get any anything at all, so can u have alook at it, please
<code>
tableData = new Vector();
Vector titles = new Vector();
int currentRow = 0;
try
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); // load the driver
conn = DriverManager.getConnection ("jdbc:microsoft:sqlserver://213.107.6.45;user=foo;password=foobar");
// connect to SQL server
conn.setCatalog("Northwind");
// choose the database
Statement stmt = conn.createStatement();
// create an SQL statement
String query = "SELECT * FROM Products;";
table = stmt.executeQuery(query);
ResultSetMetaData md = table.getMetaData();
// get the meta data
final int numberOfColumns = md.getColumnCount();
// Vector columnNames = new Vector();
// for(int i = 0; i < numberOfColumns; i++)
// columnNames.add(md.getColumnName(i+1)); //indexed from 1, not 0
// Iterator it = columnNames.iterator();
// int i = 30;
if(table.next())
//rowData(table.getObject(1).toString());
//jTextFieldField2.setText(table.getObject(2).toString());
Vector rowVector = new Vector();
for (int currentCol = 1; currentCol < numCols; currentCol++)
Object obj = table.getObject(currentCol);
rowVector.addElement(obj);
//rowVector.add(table.getString (currentCol + 1));
tableData.addAll(rowVector);
//tableData.addElement(rowVector);
//currentRow++;
for (int currentCol=1; currentCol<= numCols ; currentCol++)
titles.addElement(md.getColumnLabel(currentCol));
// Close connection to database
stmt.close();
conn.close();
}//end try
catch (Exception ex)
JOptionPane.showMessageDialog(null, ex.getMessage());
}// end catch
JTable table = new JTable(tableData,titles);
JScrollPane scrollpane = new JScrollPane(table);
this.getContentPane().add(scrollpane);
</code>
Thanks in advanceSorry i long time didn't do java coding alr , so not sure how rite i am
but in order to pass Vector into the constructor.
it had to be Vector of Vector
i.e:
Vector fieldLabel = new Vector
Vector row = new Vector();
Vector data = new Vector();
//using metadata to get the fieldname
while(rs.next()){
data.add(rs.getString("userid"));
data.add(rs.getString("subject"));
row.add(data);
JTable resultTable = new JTable(data,fieldLabel);
Not sure how useful is this.. -
Update Jtable from access database
as the title suggests help me guys... till now i have a database and some contents in it.. when the application starts the table is filled with contents of the database.. now whenever i add or remove a row in the databse i want to show it in the table... i have a Vector called dbData with the present contents of the database.. i want to update jtable with contents of dbData.... how to do it??
the best things i can see to do is
JTable table = new Jtable(.....); // this was ur table before;
deleteRow(table); // you deleted the row
// now you have a vector containing all the data for the rows;
// but you need a vector containing the columns for the rows too
//so now you do
table = new JTable(dbData,columnnames);
repaint();dbData must be a vector of vectors;
dbData.elementAt(1) return a vector with all the data for row one
so dbData.elementAt(1).elementAt(1) will be the data for row 1 column 1
// dbData will be the data still remaining in the table
or instead of the above you could use a nested for loop and set each element one at a time
Object temp;
int numberofRows = dbData.elementCount();
int numberofColumns = db.elementAt(0).elementCount();
for(int row = 0; row < numberofColumns;row++)
for( int column = 0; column < numberofRows; column++)
temp = dbData.elementAt(row).elementAt(column);
table.setValueAt(temp,row,column);
} -
Implement paging (prev/next) for jtable data obtained from database
Hello all, first time poster and relative newbie to java.
I am trying to learn java and in the process have stumbled upon this issue.
I have searched through the forum as well as googled my way around for answers. And though I am more informed than I was, I still am a little stumped.
I would like to implement a table that pulls data from a database (mysql), limits the results, and include prev/next buttons to traverse through the records.
I think this involves writing my own AbstractTableModel. And I have seen some examples as such. But could use a little more help.
I will always be pulling 10 rows, but the columns will change depending on query I am using so implementing a more generic set of methods would be great.. To be specific...
Table: users
Columns: userid, ufname, ulname, utype, ustatus, etc....
For selection purposes I only need to show: userid, ufname, ulname. So I figure I write a query like:
select userid, ulname, ufname from users limit index, 10
Where index tells the query where to start from then use the results to populate the jtable. I can do this statically but do not quite understand how to implement the next/prev buttons so that the table pulls the next or previous set of data.
If this can happen without the need to repaint/refresh the frame that would be great.
sudo code (with comments) would be ok, but a basic working example of this would be even better.
thank you in advance, if more information is required please let me know.tumbleweeds roll by...........
-
How to connect JTable to a database to show it?
al salamo 3alaykom w ra7mato allahe w barakato....
I tried a lot to connect a JTable to a database to show it.....but i couldnt......
in the clas where i create it i wrote this code
Class General extends JFrame{
// private declaration like:
private Vector heading = new Vector();
private Vector data= new Vector();
private JScrollPane jScrollPane1 = new JScrollPane();
private JTable jTable1 = new JTable(data,heading);
public General() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
private void jbInit() throws Exception {
try{
Connection conc;
DriverManager.registerDriver((Driver)Class.forName("com.mysql.jdbc.Driver").newInstance());
conc = DriverManager.getConnection("jdbc:mysql://localhost/tdiary?user=root&useUnicode=true&characterEncoding=utf8");
Statement stmt = conc.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM diary");
String n1 = new String();
String add = new String();
String tele1 = new String();
String tele2 = new String();
String tele3 = new String();
String tele4 = new String();
String mobi1 = new String();
String mobi2 = new String();
String mobi3 = new String();
String mobi4 = new String();
String mail1 = new String();
String Details = new String();
while(rs.next())
n1 = rs.getString("Name");
add = rs.getString("Address");
tele1 = rs.getString("Tel1");
tele2 = rs.getString("Tel2");
tele3 = rs.getString("Tel3");
tele4 = rs.getString("Tel4");
mobi1 = rs.getString("Mob1");
mobi2 = rs.getString("Mob2");
mobi3 = rs.getString("Mob3");
mobi4 = rs.getString("Mob4");
mail1 = rs.getString("Mail");
Details = rs.getString("Details");
heading.addElement("name");
heading.addElement("Tel");
heading.addElement("Mobile");
heading.addElement("Address");
heading.addElement("E-mail");
data.addElement(n1);
data.addElement(tele1);
data.addElement(mobi1);
data.addElement(add);
data.addElement(mail1);
System.out.println(data);
} catch (Exception k){
k.printStackTrace();
//and then i continued the code ......
//but the table doesnt appear....why?....and if there is another way to do it...plz tell me
i hope someone could help me coz i got mad from this problem.
thanx
al salamo 3alaykom w ra7mato allahe w barakatoHi,
Please use code formatting when you post code. See the formattings tips:
http://forum.java.sun.com/help.jspa?sec=formatting
I can't see that you have added your table or scroll pane to any content pane. That's why it isn't displayed.
Kaj
Ps.
You have lots of assignements of Strings when you are declaring your variables, it's useless, just set them to null.
Maybe you are looking for
-
I still have my iPod nano 3rd generation, but my old computer crashed and I did not have itunes backed up. Is there a way to get the music from ipod to new computer library and then on to the new ipod ?
-
Preview in browser not working since update
Since I updated to Muse cc 2014 the program locks when I try to preview in browser. A massage stating that "Adobe muse CC has encountered an error and will exit" appears followed by "pendingProcessInfo not found in pending processes", I then have to
-
Flip/rotate Image which is stored as BFILE in DB
Experts, Can anyone please help to achieve flipping and rotating an image. Is this can be achieved with the available adf components?. Please let me know in detail.Am using Jdeveloper 11.1.1.6.0 Thanks in advance
-
Firefox will not open today, it hangs, google chrome is fine
Firefox launches with telegraph.co.uk as default. No problems before. Today it hangs and even trying to delete telegraph.co.uk doesn't work , at least one second to delete one character, then if I type in igindex.co.uk and press return, it just hangs
-
I am taking an 8mm film to "Editran" to transfer onto a hard drive. They will have to format my HD for a PC and then transfer the movie. I am hoping to be able to get this file into iMovie HD to edit. Anyone try this before? Can a PC formatted HD be