a bug of JTable.columnMoved method - java

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

Related

jTable boolean column shows true/false instead of checkboxes

I am creating a netbeans java project that retrieves data from a microsoft access database.
I need to display an editable checkbox for one of my columns but for some reason it comes up as true/false instead. The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.
I really don't understand editors and renders though I have tried, a solution without this would be preferable but if it is the only way, please explain how to do it.
Here is my GUI code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package timetable;
/**
*
* #author Lenovo
*/
public class TaskFrame extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public TaskFrame() {
initComponents();
this.setLocationRelativeTo(null);
taskList t = new taskList()
jtblTodayTasks.setModel(t.filljtblTodayTasks());
}
/**
* 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();
jtblTodayTasks = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setMinimumSize(new java.awt.Dimension(1100, 619));
setResizable(false);
setSize(new java.awt.Dimension(1100, 619));
getContentPane().setLayout(null);
jtblTodayTasks.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jtblTodayTasks.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}
},
new String [] {
"ID", "Task", "Subject", "Due Date", "Completed"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jtblTodayTasks);
if (jtblTodayTasks.getColumnModel().getColumnCount() > 0) {
jtblTodayTasks.getColumnModel().getColumn(4).setPreferredWidth(0);
}
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(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TaskFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TaskFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jtblTodayTasks;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration
}
Here is my taskList class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package timetable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Lenovo
*/
public class taskList {
ArrayList<Task> taskArray = new ArrayList<>();
public taskList(){
ConnectDB db = new ConnectDB();
ResultSet rs = db.getResults("SELECT * FROM tblTasks WHERE userID = " + Login.currentUserID + " ORDER BY dueDate;");
try{
while (rs.next()){
Task task = new Task(rs.getInt("taskID"), rs.getInt("userID"), rs.getString("taskName"), rs.getString("Subject"), rs.getString("taskDetails"), rs.getString("dueDate"), rs.getBoolean("Completed"));
taskArray.add(task);
}
rs.close();
}catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Database error. Please contact the system Administrator");
}
}
public DefaultTableModel filljtblTodayTasks(){
Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (int i = 0; i < taskArray.size(); i++) {
model.addRow(new Object[]{taskArray.get(i).getTaskID(), taskArray.get(i).getTaskName(), taskArray.get(i).getSubject(), taskArray.get(i).getDueDate(), taskArray.get(i).isCompleted()});
}
return model;
}
Thank you so much!
The jTable in the Design view shows checkboxes but when I run the program true/false is displayed.
The getColumnClass(...) method determines which renderer is used for each column
The code in your TaskFrame already creates a custom model and overrides the getColumnClass(...) method.
But then you create another table model but are not overriding the getColumnClass(...) method:
Object[] columnNames = {"ID", "Task", "Subject", "Due Date", "Completed"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
Don't create a new DefaultTableModel.
Instead you can just use:
DefaultTableModel model = (DefaultTableModel)jtblTodayTasks.getModel();
model.setRowCount( 0 );
The above code will remove the data from the existing model, so you can add new data.

How to display username after login in Java?

I want to display username in a jLabelon welcome jFrame when user is successfully logged in. I'm doing this project with Netbeans and used DBMS is MySQL. Basically I created two jFrames.
One as login.java and other as welcome.java. The jLabel is placed in welcome.java and variable name initialized as jLabel_UnameDisplay.
Here is picture explanation of my requirement and total codes of the project:
login.java
public class login extends javax.swing.JFrame {
public login() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel = new javax.swing.JPanel();
jLabel_uname = new javax.swing.JLabel();
jLabel_pass = new javax.swing.JLabel();
txt_uname = new javax.swing.JTextField();
txt_pass = new javax.swing.JPasswordField();
jButton_login = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel_uname.setText("User Name");
jPanel.add(jLabel_uname, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 110, 100, 40));
jLabel_pass.setText("Password");
jPanel.add(jLabel_pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 170, 100, 40));
jPanel.add(txt_uname, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 110, 160, 40));
jPanel.add(txt_pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 160, 40));
jButton_login.setText("Login");
jButton_login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_loginActionPerformed(evt);
}
});
jPanel.add(jButton_login, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 230, 90, 40));
getContentPane().add(jPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
pack();
}
private void jButton_loginActionPerformed(java.awt.event.ActionEvent evt) {
if (txt_uname.getText().equals("admin")&&txt_pass.getText().equals("1234")){
new welcome().setVisible(true);
this.dispose();
}else{
try {
Connection c;
Class.forName("com.mysql.jdbc.Driver");
c=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123");
Statement s=c.createStatement();
ResultSet rs= s.executeQuery("SELECT * FROM user WHERE status='1'");
while (rs.next()) {
String unmae=rs.getString("username");
String pass=rs.getString("password");
if(unmae.equals(txtuname.getText()) && pass.equals(txtpass.getText())){
new welcome().setVisible(true);
this.dispose();
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(rootPane, "Check Your Username or Password","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new login().setVisible(true);
}
});
}
private javax.swing.JButton jButton_login;
private javax.swing.JLabel jLabel_pass;
private javax.swing.JLabel jLabel_uname;
private javax.swing.JPanel jPanel;
private javax.swing.JPasswordField txt_pass;
private javax.swing.JTextField txt_uname;
}
welcome.java
public class welcome extends javax.swing.JFrame {
public welcome() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel = new javax.swing.JPanel();
jLabel_UnameDisplay = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel_UnameDisplay.setBackground(new java.awt.Color(102, 255, 102));
jLabel_UnameDisplay.setOpaque(true);
jPanel.add(jLabel_UnameDisplay, new org.netbeans.lib.awtextra.AbsoluteConstraints(93, 69, 199, 126));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
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(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new welcome().setVisible(true);
}
});
}
private javax.swing.JLabel jLabel_UnameDisplay;
private javax.swing.JPanel jPanel;
}
There's a number of ways you might do it, but what you want to aim for is decoupling the login frame from the welcome frame, so that the decision to show one is not made by the other.
You could
Use some kind of observer/delegate/listener that is notified when the user is correctly authenticated, passing the user information to it. It would then be it's responsibility to decide what to do next, in this, show the welcome view, passing it the user information (as an example)
This is common concept in Swing
You could
Use some kind of dialog (instead of a JFrame) which would allow the code to block at the point the dialog is made visible and continuing when it's closed.
In this case, you would need to provide some kind of getter to get the user details (or null if the user cancelled the dialog for some reason), you would then be able to make a decision about what to do based on the result
Have a look at How to use dialogs for more details.
In any case, you will need to be able to pass the information in the login view to the welcome view, the means is generally very common, make use of setters and getters and basic method calling.
The easiest way is to pass the user name to the next frame on creation. So that next fame like welcome-page can use the user name. You can also pass a whole object that can store more user-specific data.
Here is the code samples. Make thin change in welcome page
/**
* Create the frame and pass the parameter during creation
*/
public welcome (Component parent, String logOnUserName) {
this.parent = parent; // This is to send the reference of parent login
// page. This can be useful if you want to
// comeback to loginpage
this.logOnUserName=logOnUserName;
...
And while calling the welcome page from login make this change
new login(this, username).setVisible(true);
Now username is available in the welcome page. Show it in UI.
I have best answer of this question. When you click on Login button then you have to specify there new frame then go to database and choose which column you want to display on after login frame. You can display with using JLable. Also you can provide reference of this video :
https://youtu.be/vlYLzCzZigg

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 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?

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