This code have created jTable that connected with a database.every cell of last column have a button.But this button doesn't work properly.Where is the error

This code have created jTable that connected with a database.every cell of last column have a button.But this button doesn't work properly.Where is the error

import java.awt.Component;

import java.awt.EventQueue;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.swing.JOptionPane;

import javax.swing.JFrame;

import javax.swing.JTable;

import javax.swing.JScrollPane;

import javax.swing.RowFilter;

import javax.swing.table.DefaultTableModel;

import javax.swing.table.TableRowSorter;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.awt.event.MouseEvent;

import java.text.NumberFormat;

import java.util.EventObject;

import javax.swing.AbstractCellEditor;

import javax.swing.JDialog;

import javax.swing.table.TableCellEditor;

import javax.swing.table.TableCellRenderer;

import javax.swing.table.TableColumn;

import javax.swing.table.TableColumnModel;

public class M extends javax.swing.JFrame {

DefaultTableModel model;

Connection connect;

Statement s;

private ResultSet rst;

int row;
String expr;

final String delete="Delete";

final TableRowSorter<DefaultTableModel> sorter;

static TableColumnModel colModel;

/**
 * Creates new form M
 */
public M() {
    initComponents();
    model = (DefaultTableModel)jTable1.getModel();
    sorter = new TableRowSorter<DefaultTableModel> (model);


try {

    Class.forName("com.mysql.jdbc.Driver");

    connect =  DriverManager.getConnection("jdbc:mysql://localhost/SORTS","root",null);

    s = connect.createStatement();



    String sql = "SELECT * FROM  member";

    ResultSet rec = s.executeQuery(sql);

      row = 0;

    while((rec!=null) && (rec.next()))

    {          

    model.addRow(new Object[0]);

    model.setValueAt(rec.getString("memberShipNo"), row, 0);

    model.setValueAt(rec.getString("name"), row, 1);

    model.setValueAt(rec.getString("workingStation"), row, 2);

    model.setValueAt(rec.getString("address"), row, 3);

    model.setValueAt(rec.getString("teleNo"), row, 4);

    model.setValueAt(rec.getString("email"), row, 5);

     model.setValueAt(delete, row, 6);

     row++;

    }

    rec.close();

    } catch (Exception e) {


        JOptionPane.showMessageDialog(null, e.getMessage());

        e.printStackTrace();

    }

    try {

        if(s != null) {

        s.close();

        connect.close();

    }

    }   catch (SQLException e) {

            e.printStackTrace();

    }


    jTable1.setRowSorter(sorter); 

                 colModel = jTable1.getColumnModel();
                 colModel.getColumn(6).setCellEditor(new ButtonEditor1(jTable1));
                 colModel.getColumn(6).setCellRenderer(new ButtonRenderer1());





}


@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();
    jButton2 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4", "5", "6", "7"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    jScrollPane1.setViewportView(jTable1);

    jButton1.setText("jButton1");

    jButton2.setText("View All");

    jTextField1.setText("");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 25, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton2)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addGap(38, 38, 38))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(75, 75, 75)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jButton2)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 90, 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(M.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(M.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(M.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(M.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 M().setVisible(true);

        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration

} ///////////////////////////////////////////////// class ButtonEditor1 extends AbstractCellEditor implements TableCellEditor, ActionListener {

javax.swing.JTable jTable1;
JButton button = new JButton();
NumberFormat nf = NumberFormat.getCurrencyInstance();
int clickCountToStart = 1;

public ButtonEditor1(javax.swing.JTable jTable1) {
    this.jTable1 = jTable1;
    button.setBackground(new java.awt.Color(255, 51, 102));
    button.setFont(new java.awt.Font("Ravie", 1, 14));
    button.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {
      System.out.println("clicked");

}

public Component getTableCellEditorComponent(javax.swing.JTable jTable1,
                                             Object value,
                                             boolean isSelected,
                                             int row, int column) {
    button.setText(value.toString());

    return button;
}

public Object getCellEditorValue() {
    return button.getText();
}

public boolean isCellEditable(EventObject anEvent) {
    if(anEvent instanceof MouseEvent) { 
        return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
    }
    return true;
}

public boolean shouldSelectCell(EventObject anEvent) {
    return true;
}

public boolean stopCellEditing() {
    return super.stopCellEditing();
}

public void cancelCellEditing() {
    super.cancelCellEditing();
}

} ///////////////////////////////////////////////////////////////////

class ButtonRenderer1 implements TableCellRenderer { JButton button = new JButton();

public Component getTableCellRendererComponent(javax.swing.JTable jTable1,
                                               Object value,
                                               boolean isSelected,
                                               boolean hasFocus,
                                               int row, int column) {
    System.out.println(hasFocus);
    button.setBackground(new java.awt.Color(255, 51, 102));
   button.setFont(new java.awt.Font("Ravie", 1, 14));
    button.setText(value.toString());
    return button;
}

}

View Answers









Related Tutorials/Questions & Answers:
NoughtsAndCrossesGame play button doesn't work
NoughtsAndCrossesGame play button doesn't work   /* * To change... if the button in btnKeypad array in positions i, j, k * all have the same text... main(String[] args) { // TODO code application logic here
NoughtsAndCrossesGame play button doesn't work
NoughtsAndCrossesGame play button doesn't work   /* * To change... if the button in btnKeypad array in positions i, j, k * all have the same text... main(String[] args) { // TODO code application logic here
Advertisements
Enabling Row, Column and Cell Selections in a JTable
Enabling Row, Column and Cell Selections in a JTable... to describe how to enable the row, column and cell selections in a JTable... will see the enabling row, column and cell selections in a JTable. When you
i have created interface program for simple arithmetic operation but its show some error can i get reason and mistakes
i have created interface program for simple arithmetic operation but its show some error can i get reason and mistakes  import java.io.*; interface... is your code, we have modified it. import java.io.*; interface arith { int a=5
i have created interface program for simple arithmetic operation but its show some error can i get reason and mistakes
i have created interface program for simple arithmetic operation but its show some error can i get reason and mistakes  import java.io.*; interface... is your code, we have modified it. import java.io.*; interface arith { int a=5
What jobs have the best work life balance?
What jobs have the best work life balance?  Hi, I am beginner... to learn: What jobs have the best work life balance? Try to provide me good examples or tutorials links so that I can learn the topic "What jobs have the best
Create a Custom Cell Renderer in a JTable
of a JTable.   row: This is the row of cell renderer.   column... Create a Custom Cell Renderer in a JTable   ... cell renderer in a JTable component. Here, first of all you will know about
Setting Cell Values in JTable
about JTable. A cell is known as the format of  a row and a column in ... the data in the specified location in terms of cell address in the JTable. We have... the given value in a cell of  JTable at the specified row and column
How to create a JTable cell containing Image hyperlink?
image (cell) in the last column of my table? so that, when the image link...How to create a JTable cell containing Image hyperlink?  I'm trying to find out how to create a JTable cell which contains Image, which should
JTable-Selecting a given cell - Swing AWT
JTable-Selecting a given cell  I tried the previous JTableDemo program but how to select a particular cell when i know the row,column number when button is clicked
JTable - Cell selection - Swing AWT
JTable - Cell selection  How to select a cell of a JTable when I clicked a button?  Hi friend, import java.awt.*; import... javax.swing.event.*; public class JTableDemo extends JFrame { JTable table
software or i have to write a code for this suff
convert windows picture or fax viewer file into ms word or pdf   sir i want to convert windows picture or fax viewer file into ms word or pdf so for this is i have to take help from the java code or any software is present
Need to have a Java Code - Java Beginners
Need to have a Java Code  Dear Friend, Can we run a unix command like "df -tg" in a remote linux system through FTP server using Java Program? Kindly give me the solution for the above query. Thanks & Regards
Getting Cell Values in a JTable
value  at a specified row and column position in JTable. The cell values... Getting Cell Values in a JTable     ... values in a JTable component. It is a same as setting the cell values in a JTable
JTable Cell Validation? - Swing AWT
JTable Cell Validation?  hi there please i want a simple example of JTable with 3 columns Name,Number,Price and the first columns is string... in the second or third column error message appear,and if you don't change the value
hi .. need help ASAP ..i have a project buit in eclipse , i have installed jasper. i want the steps to work on it ..
hi .. need help ASAP ..i have a project buit in eclipse , i have installed jasper. i want the steps to work on it ..   hi .. need help ASAP ..i have a project buit in eclipse , i have installed jasper. i want the steps to work
sum of all values in a column of jtable
sum of all values in a column of jtable  hey everyone, is there a code to display the sum of all values in a column of a jtable namely CARTtbl...("Setting Cell Values in JTable"); JPanel panel = new JPanel(); Integer data
How to delete and update from Jtable cell in swing app
How to delete and update from Jtable cell in swing app  Hii Sir... on delete button on selecting particular row which has to be deleted then last row... name,Last name etc.. My Database column structure is :presid(int),firstname
i have got error while compiling simple tag handler
i have got error while compiling simple tag handler   ... class   The package you have used javac.servlet.jsp does not exist...;it is : javax.servlet.jsp only but getting error wt is reason
How to update record to database? I have trouble with the following code
How to update record to database? I have trouble with the following code  I have written the update statement but it still not work to update the record,what is the missing of the following code ?I need help,thankyou <?php
Change Password Code in JSP
code in jsp. First of all we have created a form where we have displayed...;confirmpassword" and a Submit Form button. We have used JavaScript validation... correctly.ADS_TO_REPLACE_1 We have a created database and we create password
Changing the Name of Column in a JTable
the name of column in JTable component. You have learnt the JTable containing ... Changing the Name of Column in a JTable   ... the name of column, you must have to change the column header. For changing the name
Inserting a Column in JTable
to insert a column in JTable at a specified location. As, you have learnt in previous... column of  JTable will add in the append position. So, you must have to move... the position of column in JTable. Look at this.  Description of code: moveColumn
Appending a Column in JTable
in JTable. For adding a new column in JTable component you have to need a table model... Appending a Column in JTable     ... column in JTable. The following program creates a table that contains some data
Setting the Column Header in JTable
Setting the Column Header in JTable   ... the creation of JTable without column headers. In this example you will learn how to set the column headers in JTable using JTableHeader. Java provides some
Removing a Column from a JTable
This program helps you in how to remove a column from a JTable. For this, have... Removing a Column from a JTable     ... from a JTable component that uses the table model. Removing a column from a JTable
Moving a Column in JTable
Moving a Column in JTable       This section describes, how to move a column in JTable... the first column of  JTable. The  moveColumn method  takes the index
Java error code
that help you in understanding a Java error code. For this we have a class name 'Error code'. Inside the main method we have an array list that is used to store... Java error code     
i have one txt field and one button.when i entere any test in testfield then only button should be enabled.
i have one txt field and one button.when i entere any test in testfield then only button should be enabled.  i have one txt field and one button.when i entere any test in testfield then only button should be enabled. i need
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  Hello Sir, I have developed a swing application in which database table is shown in the jtable.. of my jframe window.Now as per my requirement i have to add
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  Hello Sir, I have developed a swing application in which database table is shown in the jtable.. of my jframe window.Now as per my requirement i have to add
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  Hello Sir, I have developed a swing application in which database table is shown in the jtable.. of my jframe window.Now as per my requirement i have to add
I have problem in my Project
I have problem in my Project  Dear Sir, i have problem in my project about Jtable i have EDIT JButton whenevery i... any sir give me this code
I have crude application
I have crude application   I have crude application, how to load into this roseindia.net
i have one txt field and one button.when i entere any test in testfield then only button should be enabled. i need for this
i have one txt field and one button.when i entere any test in testfield then only button should be enabled. i need for this   i have one txt field and one button.when i entere any test in testfield then only button should
i have problem with classnofounderror
i have problem with classnofounderror   import java.sql.*; public class Tyagi { public static void main (String args[])throws SQLException { ResultSet rs; try { Class.forName
i have problem with classnofounderror
i have problem with classnofounderror   import java.sql.*; public class Tyagi { public static void main (String args[])throws SQLException { ResultSet rs; try { Class.forName
I have need to help
I have need to help  Write a program that, for four points A, B, C and P, draws a triangle formed by ABC and a small cross showing the position of P; and displays a line of text indicating which of the following three cases
If statement doesn't work ,(doesn't print alert message when user dont field name and email)
If statement doesn't work ,(doesn't print alert message when user dont field name and email)  I've created some if / else statements to get a download when a user hit click jf he fields name and email but doesn"t work for my site
I have doubt in jsp file.
I have doubt in jsp file.  I have doubt in jsp file. In a jsp file... we click on start button, stop should be enabled and start should be disabled. When we click on stop button, start should be enabled and stop should be disabled
JTable
JTable  Hi I have problems in setting values to a cell in Jtable... i enter id in a column. and i want to load other table columns the values which i have retrieved. (adsbygoogle = window.adsbygoogle || []).push
How to add a columns with a button set to a Jtable built with database result set
How to add a columns with a button set to a Jtable built with database result set  hi, i have to build a gui to display account numbers and account... that button column to the table which is built with database result set. i would thank
Will i be able to get the content of a webpage in a word document (Note:i don t have access to the source code)through java code?
have access to the source code)through java code?  public class... am getting output to this code as html tags.... But what i want is in a word document to the webpage(for which i don t have access to source code
Shading Columns in JTable
components. Then you have to get a colorful column of JTable. Here is the code...; the rows in JTable. So, you are now capable for setting the shading the column...() method. The following code helps you for setting the shading columns in JTable
Column count doesn't match value count at row 1
Column count doesn't match value count at row 1  Column count doesn't match value count at row 1 UPDATE user_profile SET id=[value-1],user_id=[value-2],full_name=[value-3],mobile_phone=[value-4],hide_email_id=[value-5],hide
HTML Login Page Code
HTML Login Page Code Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank. We have used
Change Column Name in MySQL
.style1 { color: #0000FF; } Change Column Name in MySQL In this example How to change column name in MySQL. First of all we have created MySQL...: This is a name of the table in which we have to change the column name. old
After Logout Back Button Should not work again
After Logout Back Button Should not work again  Hi deepak,, I am doing Login Page,.. IN That If Logout Then When I Click Logout Button It Should not work.. For That what is the logic And what Concept I have To Use.. Please
JTable with Date Picker
JTable with Date Picker  Hi, I'd like to implement the following but I have no idea where to start: I have a JTable with 1 column containing Date.ADS_TO_REPLACE_1 Now i'd like the cells in this column to be editable. I have
Setting an Icon with Text in a Column Head of JTable
Setting an Icon with Text in a Column Head of JTable... to set an icon with text in a column head of JTable component. But what... a JTable containing some data and column with column header. After that you

Ads