Retrieve Data from MySQL DB and show in JTable - java

I am using the following code for retrieving the data from MySQL Database. The code connects to the database properly. My problem is in retrieving the data from MySQL DB and showing it in the JTable.
package student;
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
public class student1 extends javax.swing.JFrame {
// public Connection Conn;
Vector data = new Vector() ;
Vector columnNames= new Vector();
public student1() {
initComponents();
Connection conn;
}
public void Connection(){
try
{
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
String password = "root";
String Database = "jdbc:mysql://localhost:3306/project";
Connection conn = DriverManager.getConnection(Database, username, password);
System.out.println("*** Connect to the database ***");
String Query = "Select * from StudentMaster";
Statement smnt = conn.createStatement();
ResultSet results = smnt.executeQuery( Query );
ResultSetMetaData metaDt = results.getMetaData();
System.out.println(metaDt);
int cols = metaDt.getColumnCount();
System.out.println("database" +cols);
for(int i=1;i<cols;i++){
columnNames.addElement (metaDt.getColumnName(i));
}
while(results.next()){
Vector row= new Vector(cols);
for(int i=1;i<=cols;i++){
row.addElement(results.getObject(i));
}
data.addElement(row);
}
results.close();
smnt.close();
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"StudId", "StudNo", "StudName", "StudClass", "StudMrk1", "StudMrk2", "StudTot", "StudRes"
}
){
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(212, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new student1().setVisible(true);
student1 s1=new student1();
s1.Connection();
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
When this code is I executed, I get the following output. How can I solve my problem?
*** Connect to the database ***
com.mysql.jdbc.ResultSetMetaData#1194a4e - Field level information:
com.mysql.jdbc.Field#15d56d5[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudId,originalColumnName=StudId,mysqlType=3(FIELD_TYPE_LONG),flags= PRIMARY_KEY, charsetIndex=63, charsetName=US-ASCII]
com.mysql.jdbc.Field#efd552[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudNo,originalColumnName=StudNo,mysqlType=3(FIELD_TYPE_LONG),flags=, charsetIndex=63, charsetName=US-ASCII]
com.mysql.jdbc.Field#19dfbff[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudName,originalColumnName=StudName,mysqlType=253(FIELD_TYPE_VAR_STRING),flags=, charsetIndex=8, charsetName=Cp1252]
com.mysql.jdbc.Field#10b4b2f[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudClass,originalColumnName=StudClass,mysqlType=253(FIELD_TYPE_VAR_STRING),flags=, charsetIndex=8, charsetName=Cp1252]
com.mysql.jdbc.Field#750159[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudMrk1,originalColumnName=StudMrk1,mysqlType=3(FIELD_TYPE_LONG),flags=, charsetIndex=63, charsetName=US-ASCII]
com.mysql.jdbc.Field#1abab88[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudMrk2,originalColumnName=StudMrk2,mysqlType=3(FIELD_TYPE_LONG),flags=, charsetIndex=63, charsetName=US-ASCII]
com.mysql.jdbc.Field#18a7efd[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudTot,originalColumnName=StudTot,mysqlType=3(FIELD_TYPE_LONG),flags=, charsetIndex=63, charsetName=US-ASCII]
com.mysql.jdbc.Field#1971afc[catalog=project,tableName=StudentMaster,originalTableName=studentmaster,columnName=StudRes,originalColumnName=StudRes,mysqlType=253(FIELD_TYPE_VAR_STRING),flags=, charsetIndex=8, charsetName=Cp1252]
database8
BUILD SUCCESSFUL (total time: 14 seconds)

I don't see any errors. What you see are the messages that are being printed from within your code, primarily from these statements:
ResultSetMetaData metaDt = results.getMetaData();
System.out.println(metaDt);
int cols = metaDt.getColumnCount();
System.out.println("database" +cols);

Your basic code looks reasonable. You create two Vectors containing the columns names and data, but no where do you then use these Vectors to create a DefaultTableModel which can then be added to the table.
So your code should be something like:
conn.close();
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel( model );
For a complete example (using Access) check out the Table From Database Example found in Table From Database.

Related

JDBC to JTable output query regarding making buttons work in GUI Editor for Netbeans

so, i'm working on a project where I have to use a search button to find user information from a jdbc database, and so far I've got some of the code to work and added fields and data to the database, but once i hit search in the jtextfield it doesn't display any data in the table. So, i'm wondering if someone can take a look at this code and tell me where the mistake is, the jbutton is supposed to connect to the mainframe where the database connection information is stored.
this is the main frame code:
package guestbook;
import java.sql.Connection;
import java.sql.DriverManager;
public class MainFrame extends javax.swing.JFrame {
public static String dbURL = "jdbc:derby://localhost:1527/Coolkidsclub;create=true;user=Vic";
public static Connection conn = null;
/**
* Creates new form MainFrame
*/
public MainFrame() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();//"org.apache.derby.jdbc.ClientDriver" to use derby driver
conn = DriverManager.getConnection(dbURL);
initComponents();
}
catch (Exception e){
}
initComponents();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/ckc.PNG"))); // NOI18N
jButton1.setText("Add Kid");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Update Kid");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Remove Kid");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Find Kid");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jLabel1)
.addContainerGap(109, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addGap(130, 130, 130))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(44, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
AddFrame add = new AddFrame();
add.setVisible(true);
this.dispose();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
UpdateFrame update = new UpdateFrame();
update.setVisible(true);
this.dispose();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
RemoveFrame remove = new RemoveFrame();
remove.setVisible(true);
this.dispose();
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
SearchFrame search = new SearchFrame();
search.setVisible(true);
this.dispose();
}
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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
and this is the searchframe code:
package guestbook;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class SearchFrame extends javax.swing.JFrame {
public SearchFrame() {
initComponents();
}
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jTable1.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"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/fckc.PNG"))); // NOI18N
jTextField1.setText("Type Name Here...");
jButton5.setText("Find Kid");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("Go back to Start");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jTable2.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 [] {
"", "", "", ""
}
));
jTable2.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)))))
.addGroup(layout.createSequentialGroup()
.addGap(294, 294, 294)
.addComponent(jButton6)))
.addContainerGap(146, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton6)
.addContainerGap(58, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Statement stmt = MainFrame.conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
jTable2.setModel(buildTableModel(rs));//to display the table
} catch (Exception except) {
}
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
MainFrame main = new MainFrame();
main.setVisible(true);
this.dispose();
}
/**
* #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(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SearchFrame.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() {
new SearchFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
any help would be greatly appreciated as I'm relatively new to java.
EDIT: After a day or two I did a stackTrace exception printout and it says something about the statement stmt code being wrong do i just need to add a line in the searchframe to connect to the database and forget the mainframe connection?
So, i'm wondering if someone can take a look at this code and tell me where the mistake is, the jbutton is supposed to connect to the
mainframe where the database connection information is stored.
Well the first thing I can say is it's a lot of code. Now, there are several conceptual mistakes in your code that may lead to the stated problem.
Don't mix View (user interface) with Database connections
Beware that applications are tipically designed using layers or levels to isolate and separate responsibilities. In this case having a static Connection object within a JFrame simply breaks this principle. The first thing to do is separate database connection and logic from the user interface.
Don't ignore exceptions, always give them a correct treatment
This one of the worse things we can do:
try {
...
} catch (Exception e) {}
If an exception has been thrown it means that something unexpected happened. Just ignoring the exception in an empty catch block won't make it be solved but will hide this fact to us. Consequently we won't be able to solve the problem because we don't actually know that something wrong is heppening.
Avoid using static references
If you need to use a static to access a class member then it's probably there's a design problem in our code. While static fields are possible and sometimes useful (i.e.: define constants) from an OOP point of view they are not a good choice because break the encapsulation principle. We can just give access to a class member to the outside by providing getters and setters.
EDIT: After a day or two I did a stackTrace exception printout and it says something about the statement stmt code being wrong do i just
need to add a line in the searchframe to connect to the database and
forget the mainframe connection?
You would have to include the stack trace in your question, but let's take a look to the SQL query sent to the database:
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
Most likely there is a WHERE clause missing in your SQL statmement (I don't know the text obtained from jTextField1 so it's just a guess). SQL statments tipically have this minimal structure:
SELECT fields list
FROM tables
WHERE conditions
On the other hand you might consider use PreparedStatement like this:
String sql = "SELECT * FROM coolkids WHERE name = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
ResultSet rs = pst.executeQuery();
Once again, this code should be isolated from the UI and jTextField1 text should be passed as an argument to an appropriate Controller/Persistence layer class.

Disposing a Modal dialog using a condition

I have a modal jDialog that i wish to dispose when a particular condition is met after showing the error message in another Dialog using JOptionPane. I have tried to use the dispose() method after the JOptionPane dialog but my modal dialog still opens up.
The relevant part of my code is below:
import java.awt.Component;
import java.sql.*;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class ReviewPatients extends javax.swing.JDialog {
public ReviewPatients(java.awt.Frame parent, boolean modal) {
super(parent, modal);
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Name", "Address", "Number"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1012, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
jScrollPane1.setVisible(false);
e:
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3307/doctor","root","Pranav123");
String query="SELECT * FROM records_table WHERE Name LIKE 'some_name';";
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();
//Clearing the table
int rows=tmodel.getRowCount();
while(rows>0)
{
tmodel.removeRow(0);
rows--;
}
jTable1.setModel(tmodel);
while(rs.next())
{
//Putting data into table
tmodel.addRow(new Object[] {rs.getString(1),rs.getString(2),rs.getInt(4)});
jTable1.setModel(tmodel);
}
}
catch(Exception e)
{
System.out.println("Error: "+e);
}
if(jTable1.getRowCount()==0)
{
JOptionPane.showMessageDialog(this, "No records exist!");
dispose();
break e;
}
//Showing data
jScrollPane1.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ReviewPatients dialog = new ReviewPatients(new javax.swing.JFrame(), true);
dialog.setVisible(true);
}
});
}
e is the label that I have used to exit the block whenever an error occurs.
Any help would be greatly appreciated.
All static methods in JOptionPane create modal dialogs, i.e., execution of the code stops until the user dismisses the dialog box. If you want to create non-modal dialogs, use JDialog directly. Refer to Java Swing Tutorial for more information.
Updated:
If I am not wrong, you are trying to do is to NOT show the ReviewPatients dialog at all when there are no records. If that is the case, the simplest solution is to just replacing dispose() with System.exit(1).
A better solution is check whether there are records in the database, and:
If there are records, create the ReviewPatients dialog and populate the table with the data.
If there is no record, display the JOptionPane to inform the user there is no record, and terminate the program.
On a separate note: though permissible, try not to mix AWT components with Swing components (refer to another Stack Overflow answer for the reasons).
I see a number of problems, some of which may be relevant:
Repeated calls to setModel() are unnecessary and may notify the listening table unexpectedly.
A simpler way to clear the DefaultTableModel is via setRowCount(0).
Instead of checking the view for success, check the model; even better, just show the JOptionPane in the exception handler.
The dialog's parent should probably be a JFrame.
Also consider updating the table's model using SwingWorker.
As tested:
import java.sql.*;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* #see http://stackoverflow.com/a/24220593/230513
*/
public class ReviewPatients extends javax.swing.JDialog {
public ReviewPatients(JFrame parent, boolean modal) {
super(parent, modal);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
JTable table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][]{},
new String[]{
"Name", "Address", "Number"
}
) {
Class[] types = new Class[]{
java.lang.String.class, java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean[]{
false, false, false
};
#Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(table, javax.swing.GroupLayout.PREFERRED_SIZE, 800, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(table, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
this.setLocationRelativeTo(null);
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:~/src/java/jdbc/test;IFEXISTS=TRUE", "sa", "");
String query = "SELECT * FROM CUSTOMER;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
while (rs.next()) {
model.addRow(new Object[]{rs.getInt(1), rs.getString(2), rs.getString(3)});
}
} catch (Exception e) {
System.out.println("Error: " + e);
JOptionPane.showMessageDialog(null, "No records exist!");
}
this.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
ReviewPatients dialog = new ReviewPatients(f, true);
}
});
}
}

Export Jtable in excel file

hi i am newbie in java programming but here's my problem
i am designing GUI which does some calculation and need to show the inputs and outputs in J table then export them into excel file
the code working like charm but when i open the excel file i find it empty ..
j Table
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.swing.JFileChooser;
public class Export extends javax.swing.JFrame {
public Export() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"Channel Model", global.channel_model, global.channel_model},
{"System Bandwidth (MHz)", global.band_width_index, global.band_width_index},
{"Cell Edge Rate (Kbps)", global.Rreq_UL, global.Rreq_DL},
{"Cell edge MCS", global.mcs, global.mcs},
{"Antenna Configuration", global.DL_antenna_config, global.DL_antenna_config},
{"Total RB Number", global.number_of_RB, global.number_of_RB},
{"Tx", "", null},
{"Max Power (dBm)", global.UE_Tx_power, global.UE_Tx_power},
{"Cable Loss (dB)", global.cable_loss, global.cable_loss},
{"Body Loss (dB)", global.body_loss, global.body_loss},
{"Antenna Gain (dB)", global.UE_antennaGain, global.UE_antennaGain},
{"EIRB (dB)", "", null},
{"Rx", null, null},
{"Antenna Gain (dB)", global.UE_antennaGain, global.UE_antennaGain},
{"Cable Loss (dB)", global.cable_loss, global.cable_loss},
{"Body Loss (dB)", global.body_loss, global.body_loss},
{"Noise Figure (dB)", global.UE_noiseFigure, global.UE_noiseFigure},
{"Thermal Noise (dB)", null, null},
{"Interference Margin (dB)", global.Biul, global.Bidl},
{"SINR (dB)", global.SINR, global.DL_SINR},
{"Reciver Sensitivty (dB)", "", null},
{"MAPL", null, null},
{"Diversity (dB)", global.Tx_diversity_gain, global.Tx_diversity_gain},
{"Shadow Fading Margin (dB)", global.shadow_margin, global.shadow_margin},
{"MAPL (dB)", null, null},
{"Cell Radius (Km)", global.R, global.R},
{"Area of Dimensioning (Km squar", global.site_area, global.site_area},
{"Site Type", global.type_of_site, global.type_of_site},
{"Number of Sites Due to Coverage", "", null}
},
new String [] {
"Summary", "Uplink", "Downlink"
}
));
jTable1.setName("Export");
jScrollPane1.setViewportView(jTable1);
jTable1.getAccessibleContext().setAccessibleName("\"Export\"");
jTable1.getAccessibleContext().setAccessibleDescription("");
jButton1.setText("Export");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
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(562, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
.addComponent(jScrollPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(jButton1);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".xls")) {
file = new File(file.getParentFile(), file.getName() + ".xls");
}
try {
ExcelExporter exp=new ExcelExporter();
exp.exportTable(jTable1, file);
Desktop.getDesktop().open(file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("not found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}catch(Exception e){
System.out.println("shit");
}
}
public static void main(String args[]) {
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(Export.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Export.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Export.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Export.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() {
new Export().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
The excel generator class
import java.io.*;
import javax.swing.table.TableModel;
import javax.swing.*;
public class ExcelExporter {
ExcelExporter(){}
public void exportTable(JTable jTable1,File file) throws IOException{
TableModel model=jTable1.getModel();
FileWriter out=new FileWriter(file);
BufferedWriter bw=new BufferedWriter(out);
for (int i=0;i<model.getColumnCount();i++){
bw.write(model.getColumnName(i)+"\t");
}
bw.write("\n");
for (int i=0;i<model.getRowCount();i++){
for (int j=0;j<model.getColumnCount();j++){
bw.write(model.getValueAt(i,j).toString()+"\t");
}
bw.write("\n");
}
bw.close();
System.out.print("Write out to"+file);
}
}
As has been recommended Apache POI is a very good api for manipulating and creating Excel documents. It is free and open source so easily usable. If you try it out then here is one way you could create your file:
private static void writeToExcell(JTable table, Path path) throws FileNotFoundException, IOException {
new WorkbookFactory();
Workbook wb = new XSSFWorkbook(); //Excell workbook
Sheet sheet = wb.createSheet(); //WorkSheet
Row row = sheet.createRow(2); //Row created at line 3
TableModel model = table.getModel(); //Table model
Row headerRow = sheet.createRow(0); //Create row at line 0
for(int headings = 0; headings < model.getColumnCount(); headings++){ //For each column
headerRow.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
}
for(int rows = 0; rows < model.getRowCount(); rows++){ //For each table row
for(int cols = 0; cols < table.getColumnCount(); cols++){ //For each table column
row.createCell(cols).setCellValue(model.getValueAt(rows, cols).toString()); //Write value
}
//Set the row to the next one in the sequence
row = sheet.createRow((rows + 3));
}
wb.write(new FileOutputStream(path.toString()));//Save the file
}
The alternative would be to learn the Microsoft Excel file specifications and then manually create the Excel file that way. What you are doing at the moment is writing the data in your table to a file, but not in any way that the Excel application can understand it.
For write and manipulating Excel file use Apache POI http://poi.apache.org/
If You want to create Excel file by Yourself without using external library, keep in mind that excel file data is stored in form of XML Spreadsheet, so You will have to create file like that
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="2" x:FullColumns="1" x:FullRows="1">
<Row>
<Cell><Data ss:Type="String">Name</Data></Cell>
<Cell><Data ss:Type="String">Example</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="String">Value</Data></Cell>
<Cell><Data ss:Type="Number">123</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook>
source: http://en.wikipedia.org/wiki/Microsoft_Excel
You can solve this without using Apache POI.
What worked for me was to remove the String conversion while writing in the excel exporter class.
bw.write(model.getValueAt(i,j)+"\t");
See if this works.
This is because the getValueAt() function returns an object which has a problem in conversion to String.
Let me know.

How to save edited JTable data to database?

First of all sorry for my poor English. I'll try my best to understand you my problem.
All I want is to save the new data whichever user has entered in the JTable whenever Save button will clicked.
I am retrieving Student ID, Name in first two columns from database and also i have added current date in third column and Absent/Present as fourth column which is editable. I have following code to retrieve data from database.
**Attendance.java** :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;
/**
*
* #author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
String d1 = fromUser.format(sqlDate);
String d = d1.toString();
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
PreparedStatement pre = con.prepareStatement("select studentid,name from student");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2));//name
employee.add(d);
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
**AttendanceGUI.java : **
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.sql.Connection;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* #author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
Connection con = Connectdatabase.ConnecrDb();
private Vector<Vector<String>> data;
private Vector<String> header;
public AttendanceGUI() throws Exception {
this.setLocationRelativeTo(null);
setExtendedState(MAXIMIZED_BOTH);
Attendance att = new Attendance();
data = att.getEmployee();
header = new Vector<String>();
header.add("Student ID");
header.add("Student Name");
header.add("Date");
header.add("Absent/Present");
initComponents();
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
AttendanceT = new javax.swing.JTable();
SaveAtt = new javax.swing.JButton();
Exit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
)
{public boolean isCellEditable(int row, int column){return true;}}
);
AttendanceT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(AttendanceT);
tca.adjustColumns();
AttendanceT.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(AttendanceT);
SaveAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
SaveAtt.setText("Save Attendance");
SaveAtt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveAttActionPerformed(evt);
}
});
Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
Exit.setText("Exit");
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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(176, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void SaveAttActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.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 AttendanceGUI().setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable AttendanceT;
private javax.swing.JButton Exit;
private javax.swing.JButton SaveAtt;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
This output I get when I run JFrame :
Now, What I want actually is whenever user will edit data into JTable just like in the following Image :
****After clicking Save Attendance button the current JTable values should entered into the database. I am using Sqlite database which is addon in Firefox. I have created attendance table in my database which is having studentid integer, name varchar, date DATETIME, and preab VARCHAR(This to store whether particular student was present or absent) ****
I hope that you get what my problem is. Thanks in advance.
As you are using DefaultTableModel you have to register a listener to that model a TableModelListener listening for changes. How to use TableModelListener
Example:
myTable.getModel().addTableModelListener(new TableModelListener(){
#Override
public void tableChanged(TableModelEvent evt){
//code here
}
});
public void happi(String name, String age, String id){
//this method should be located on a class, then you just instantiate the class in the main form
String query=null;
try{
query = "update tbltest set name = '"+name+"',age = '"+age+"' where id = '"+id+"'";
stmt.executeUpdate(query);
}
catch(Exception ex){JOptionPane.showMessageDialog(null,""+ex);}
finally{
super.closeConnection(connect);
super.closeStatement(stmt);
}
}//end of happi
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//a button with event ActionPerformed (save button)
table.updateUI();
}//end
private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {
// a JTablenamed"table"
try{
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
int c = table.getColumnCount();
DBHandler dbh = new DBHandler();
dbh.happi((table.getModel().getValueAt(row, 0).toString()), (table.getModel().getValueAt(row, 1).toString()), (table.getModel().getValueAt(row, 2).toString()));
}catch(Exception e){}
} '

a bug of JTable.columnMoved method

javax.swing.JTable has a bug,
if we sort the table while a null valued cell is editing,
and whose column class does not have a constructor with "new Object[] { new String() }" parameter, eg. Long.class,
the JTable will throw an exception.
I think that because javax.swing.JTable tries to remove the cell editor twice;
So I plan to override the JTable.columnMoved method as:
#Override
public void columnMoved(TableColumnModelEvent e) {
if (isEditing() && !getCellEditor().stopCellEditing()) {
if(getCellEditor() != null) { // In javax.swing.JTable, no this check point
getCellEditor().cancelCellEditing();
}
}
repaint();
}
I felt that's not good enough, since it's not friendly for code readers, they may know JTable well, and do not like my sub classes like this.
Is there a better solution?
Thanks a lot.
When running the following codes, double click one cell (do not input anything) and then click the header, the exception will show up.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Title 1", "Title 2"
}
) {
Class[] types = new Class [] {
java.lang.Long.class, java.lang.Long.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
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(jScrollPane1, 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(jScrollPane1, 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
I can reproduce the issue with the code you provided. I blame the JTable#stopCellEditing implementation
public boolean stopCellEditing() {
String s = (String)super.getCellEditorValue();
// Here we are dealing with the case where a user
// has deleted the string value in a cell, possibly
// after a failed validation. Return null, so that
// they have the option to replace the value with
// null or use escape to restore the original.
// For Strings, return "" for backward compatibility.
if ("".equals(s)) {
if (constructor.getDeclaringClass() == String.class) {
value = s;
}
super.stopCellEditing();
}
try {
value = constructor.newInstance(new Object[]{s});
}
catch (Exception e) {
((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
return super.stopCellEditing();
}
You enter the first if, where super.stopCellEditing is called. The return value of this call is ignored. Then the newInstance call throws an exception, which is catched but then false is returned, no matter what the return value was of super.stopCellEditing. This sounds incorrect to me. I would log the bug with Oracle with the code you provided
I can't see any issue, any bug, TableCellEditor is canceled properly on sorting and column reordering,
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableWithTimer {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private JScrollPane scroll = new JScrollPane();
private JTable myTable;
private String[] head = {"One", "Two", "Three", "Four", "Five", "Six"};
private Object[][] data = {{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null}};
private DefaultTableModel model;
public TableWithTimer() {
model = new DefaultTableModel(data, head) {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return Double.class;
case 2:
return Long.class;
case 3:
return Boolean.class;
default:
return String.class;
}
}
};
myTable = new JTable(model);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myTable.setGridColor(Color.gray);
myTable.setFillsViewportHeight(true);
myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
myTable.setAutoCreateRowSorter(true);
scroll.setViewportView(myTable);
frame.add(scroll, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TableWithTimer tableWithTimer = new TableWithTimer();
}
});
}
}
The issue - analyzed correctly by #Robin - has several aspects:
stopCellEditing incorrectly firing an editingStopped even when returning false
stopCellEditing firing twice if an empty value is accepted by the constructor
While the second is "just" violating its contract, the first has severe consequences:
as noted in the OP's question: throwing an NPE if client code tries to really terminate the edit, that is first stop and on failure cancel. Ironically, the most visible appearance is in jdk7 table.columnMoved - where the formerly (up to jdk6) incorrect removeEditor is replaced by the Right-Thing.
might lead to data corruption if the edit started with a valid value which is deleted while editing: the editingStopped event triggers the table to replace the valid value in the tableModel with null ...
Enough reason to fix in JXTable by different logic in GenericEditor (the fix can be used in a custom GenericEditor as well, no coupling to swingx: simply c&p core GenericEditor and replace its stopCellEditing with the following):
#Override
public boolean stopCellEditing() {
String s = (String) super.getCellEditorValue();
// JW: changed logic to hack around (core!) Issue #1535-swingx
// don't special case empty, but string contructor:
// if so, by-pass reflection altogether
if (constructor.getDeclaringClass() == String.class) {
value = s;
} else { // try instantiating a new Object with the string
try {
value = constructor.newInstance(new Object[] { s });
} catch (Exception e) {
((JComponent) getComponent()).setBorder(new LineBorder(
Color.red));
return false;
}
}
return super.stopCellEditing();
}

Categories