Export Jtable in excel file - java

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.

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.

How to reduce the loading time of an Open file using Swing?

I want to open a file without taking any time.When I click on open Button immediately it has been opened.But,In my application It has taken more than two minutes for large files.I try to open a file,It has size 44MB.This file takes more than two minutes time to open.I want to open large size files quickly.Once check my open action code.
The below code shows the working example of my Application.
Sample code:
public class OpenDemo extends javax.swing.JFrame {
JTextPane textPane;
JScrollPane scrollPane;
int i=0;
JTextField status;
public OpenDemo() {
initComponents();
textPane=new JTextPane();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
open.setText("Open");
open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openActionPerformed(evt);
}
});
jMenu1.add(open);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void openActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser=new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result==JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
textPane.setPage(file.toURI().toURL());
} catch(Exception e) {
e.printStackTrace();
}
}
scrollPane=new JScrollPane(textPane);
tp.add(scrollPane);
textPane.setCaretPosition(0);
}
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}
The SwingWorker API outlines a suitable approach. Because of the size, I'd update a TableModel, as shown here, rather than a text component. Lines will begin appearing almost immediately, while the GUI remains responsive. The listening JTable will need to render only visible lines, and you may be able to leverage sorting and filtering.
There is some overhead (progress animation) and some things I would not have done, like a AWT event thread blocking actionPerformed.
Go with your code to https://codereview.stackexchange.com/ because a code review might be useful.
What I saw as optimizable:
Give an initial capacity to the StringBuilder.
... = new StringBuilder(1024*64); // (int)file.length()?
Replace the Scanner with a BufferdReader using readLine().
Ideal would be to check the speed of Files.readAllBytes; whether a progress indication is needed.
String s = new String(Files.readAllBytes(file.toPath()));
Second attempt:
First a sanity measure: closing the file.
Then I did less progress animation, which should definitely speed things up.
It will no longer show all text in the text pane, only every hundredth line.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
final int PROGRESS_EVERY = 100;
while ((line = br.readLine()) != null) {
lineNumber++;
text.append(line);
text.append("\n");
if (linenumber % PROGRESS_EVERY== 0) {
ProgressData data = new ProgressData();
data.number = lineNumber;
data.line = line;
publish(data);
}
}
if (linenumber % PROGRESS_EVERY != 0) {
ProgressData data = new ProgressData();
data.number = lineNumber;
data.line = line;
publish(data);
}
}
And then
private StringBuilder text = new StringBuilder(1024 * 128);
At last:
Change textPane from JTextPane to JTextArea. Considerable gain in speed.

How to add JCheckBox in JTable?

First of all i apologize for my english neglect that i will explain all my problem.
First i want JCheckBox in the JTable i have.
I am retrieving student id and student name from database in column index 0 and 1. I want third column should be Absent/Present which will initially take whether student is present or absent by JCheckbox Value.
Here my code for JTable values :
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.util.Vector;
/**
*
* #author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
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
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
THIS CODE FOR TAKING VALUES FROM DATABASE SAVING IT INTO VECTOR
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.util.Vector;
import javax.swing.JOptionPane;
/**
*
* #author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
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("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();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
));
jScrollPane1.setViewportView(AttendanceT);
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)
.addContainerGap(397, Short.MAX_VALUE))
);
layout.setVerticalGroup(
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)
.addContainerGap(89, 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(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.JScrollPane jScrollPane1;
// End of variables declaration
}
My problemis that I can't add a JCheckBox in front of every student I have seen JTabel model, renderer and all but I don't get anything. I want something like this...
I've search for this stuff for a couple of weeks but did bot get anything suitable for this
Start with How to use tables.
Your table model needs several things.
It needs to return Boolean.class from the getColumnClass method for the appropriate column. You will need to override this method.
The method isCellEditable will need to return true for the table column you want to make editable (so the user can change the value of the column)
You're table model will need to be capable of holding the value for the column
Make sure you pass a valid value for the boolean column for the row, otherwise it will be null
Updated with simple example
import java.awt.EventQueue;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableTest {
public static void main(String[] args) {
new TableTest();
}
public TableTest() {
startUI();
}
public void startUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
MyTableModel model = new MyTableModel();
model.addRow(new Object[]{0, "Brian", false});
model.addRow(new Object[]{1, "Ned", false});
model.addRow(new Object[]{2, "John", false});
model.addRow(new Object[]{3, "Drogo", false});
JTable table = new JTable(model);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyTableModel extends DefaultTableModel {
public MyTableModel() {
super(new String[]{"ID", "Name", "Present"}, 0);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = Integer.class;
break;
case 2:
clazz = Boolean.class;
break;
}
return clazz;
}
#Override
public boolean isCellEditable(int row, int column) {
return column == 2;
}
#Override
public void setValueAt(Object aValue, int row, int column) {
if (aValue instanceof Boolean && column == 2) {
System.out.println(aValue);
Vector rowData = (Vector)getDataVector().get(row);
rowData.set(2, (boolean)aValue);
fireTableCellUpdated(row, column);
}
}
}
}
Ps- I would HIGHLY recommend you avoid form editors until you have a better understanding of how Swing works - IMHO
Well if you add Boolean value as data into the table model, DefaultCellRendered will render it as checbox by itself, so where is the problem?

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();
}

Retrieve Data from MySQL DB and show in JTable

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.

Categories