JTable Permenentaly Show Combo

how to show permanently combo box etc type things in JTable they only appears when when clicks on them?

Use a combo box as a renderer also and not just as an editor.

Similar Messages

  • JTable not showing up....

    Hello,
    I'm working with a JTable and having a slight problem. The JTable never shows up and I'm not sure why because when I debug it, data[][] has all the correct values. If someone could just point me in the right direction it would be greatly appreciated. Here is my code. It is self contained.
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class FillingHistoryTable extends JPanel {
        JTable fhTable;
        JScrollPane tableHolder;
        public static void main(String[] args){
            JFrame f = new JFrame("FHTABLE");
            f.getContentPane().add(new FillingHistoryTable());
            f.setVisible(true);
        public FillingHistoryTable(){
            initComponents();
        private void initComponents(){
            fhTableModel model = new fhTableModel();
            model.initModel();
            fhTable = new JTable(model);
            fhTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            fhTable.setFillsViewportHeight(true);
            tableHolder = new JScrollPane(tableHolder);
            buildComponents();
        private void buildComponents(){
            this.add(tableHolder);
            this.setVisible(true);
        class fhTableModel extends DefaultTableModel {
            private String[] columnNames = {"Year", "Waste in tons"};
            private Object[][] data;
            private int currentYear = 2008;
            private int openYear = 1998;
            private int yearsOpen = currentYear - openYear;
            public void initModel(){
                data = new Object[yearsOpen + 1][2];
                for(int row = 0; row <= yearsOpen; row++){
                    for(int col = 0; col < 2; col++){
                        if (col == 0){
                            data[row][col] = currentYear;
                        else{
                            data[row][col] = 0;
                    currentYear = currentYear - 1;
    }

    are you adding your scrollpane to itself?
    tableHolder = new JScrollPane(tableHolder);Something tells me that you need to add your JTable to a JScrollPane at some point or another.

  • Jtable not showing column Names

    I wrote the following Code and strangely it isn't showing the column Names....
    The mistake should be foolish..but i can't figure it out...
    can you please help.. or give any alternate way to do the same
    import javax.swing.*;
    import javax.swing.table.*;
    public class test
         public static String[] columnNames = {"User Name","User ID"};
         public static void main(String args[])
              JFrame frame = new JFrame();
              frame.setSize(400, 400);
              DefaultTableModel tabmodel = new DefaultTableModel(columnNames, 15);
              JTable table = new JTable(tabmodel);
              frame.add(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }

    Hi,
    A JScrollPane is needed to display the headers.
    import javax.swing.*;
    import javax.swing.table.*;
    public class TestTable {
        public static String[] columnNames = { "User Name", "User ID" };
        public static void main(String args[]) {
         // PB All GUI creation on the EDT
         SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
              JFrame frame = new JFrame();
              frame.setSize(400, 400);
              DefaultTableModel tabmodel = new DefaultTableModel(columnNames,
                   15);
              JTable table = new JTable(tabmodel);
              // PB frame.add(table);
              frame.add(new JScrollPane(table)); // PB
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }Piet

  • Problem in showing combo box in the table

    Hello guys i just add up the combo box in the table but the problem is when i change the line in the table the combo disappear. i want it to be visible even if it is not in the selected row. i want that user can see the combo box in the table without clicking on it.
    Please help;

    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    Look in the page bottom !

  • Automatically resize JTable to show entire contents of every cell

    Is there a way to automatically set the preferred size of a JTable, or its columns, such that the entire contents of all table cells are displayed? Setting the preferred widths of TableColumns myself isn't a great idea, because (a) the column's preferred width will change depending on what font the user is using, and (b) it can waste a lot of space if e.g., a column's values can theoretically be 1024 characters long but the only entries in that column currently are, say, less than 32 characters long.
    thanks for any help

    fantastic, it works beautifully. Thanks!
    (for future search reference, D.B's post is at [http://forum.java.sun.com/thread.jspa?threadID=5283356&messageID=10193297|http://forum.java.sun.com/thread.jspa?threadID=5283356&messageID=10193297])

  • Show hidden columns in a JTable

    Hi,
    I have a requirement for hiding some columns of a JTable and showing them back based on user actions.
    I have gone through some topics about hiding columns. which can be done by table.removeColumn();
    But when I use table.addColumn(); it adds the column at the end of the table.It should add in the same location as the previous column.
    How to show /reveal the hidden column back?.

    * Hide_Columns.java
    * This code contains a table model that allows you to
    * specify the columns to be hidden in a boolean array.
    * To use the model:
    *       model = new MyTableModel(data, columnNames);
    *       table.setModel(model);
    * The most important method in the model is "getNumber()", which converts a column number
    * into the number corresponding to the data to be displayed.
    * Visible columns can be dynamically changed with
    * model.setVisibleColumns(0, column0.isSelected());
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Hide_Columns extends JFrame {
        public Hide_Columns() {
            setTitle("Hide columns");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            model = new MyTableModel(data, columnNames);
            table.setModel(model);
            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
            for( int i=0; i<4; i++ ){
                final JCheckBox columnX = new JCheckBox("Column "+i);
                columnX.setSelected(true);
                final int col = i;
                columnX.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        model.setVisibleColumns(col, columnX.isSelected());
                toolBar.add(columnX);
            getContentPane().add(toolBar, BorderLayout.NORTH);
            setSize(400,300);
            setLocationRelativeTo(null);
            model.addRow(new Object[]{null,null,null,null});
            model.setValueAt("test0",0,0);
            model.setValueAt("test1",0,1);
            model.setValueAt("test2",0,2);
            model.setValueAt("test3",0,3);
        public static void main(String args[]) { new Hide_Columns().setVisible(true); }
        private JTable table = new JTable();
        private  JToolBar toolBar = new JToolBar();
        private   MyTableModel model;
        /** This is the data of the table*/
        private  Vector<Object> data = new Vector<Object>();
        /** Column names */
        Vector<String> columnNames = new Vector<String>();{
            columnNames.addElement("0");
            columnNames.addElement("1");
            columnNames.addElement("2");
            columnNames.addElement("3");
    class MyTableModel extends DefaultTableModel {
        /** Shows which columns are visible */
        private   boolean[] visibleColumns = new boolean[4];{
            visibleColumns[0] = true;
            visibleColumns[1] = true;
            visibleColumns[2] = true;
            visibleColumns[3] = true;
        public MyTableModel(Vector<Object> data, Vector<String> columnNames){
            super(data, columnNames);
        protected void setVisibleColumns(int col, boolean selection){
            visibleColumns[col] = selection;
            fireTableStructureChanged();
         * This function converts a column number of the table into
         * the right number of the data.
        protected int getNumber(int column) {
            int n = column;    // right number
            int i = 0;
            do {
                if (!(visibleColumns)) n++;
    i++;
    } while (i < n);
    // When we are on an invisible column,
    // we must go on one step
    while (!(visibleColumns[n])) n++;
    return n;
    // *** METHODS OF THE TABLE MODEL ***
    public int getColumnCount() {
    int n = 0;
    for (int i = 0; i < 4; i++)
    if (visibleColumns[i]) n++;
    return n;
    public Object getValueAt(int row, int column) {
    return super.getValueAt(row, getNumber(column));
    public void setValueAt(Object obj, int row, int column) {
    super.setValueAt(obj, row, getNumber(column));
    public String getColumnName(int column) {
    return super.getColumnName(getNumber(column));

  • Saves the word Null - Using jTable!!

    Hi..
    I am using a jTable to show data to the final user, and also i added a button which save changed made on the jTable is the user modifies it!! But, if i save it with in the ms access saves the word null when it finds an empty space.. why this happens? here is the code.. and sometimes it didn't work well on somefields, that why i use vectors, and now it is working.. but i am still wondering why if a field was empty, when i click on the save button it saved the word null.
    Thanks for your attention,
    Xavier Arroyo
    * Main.java
    * Created on March 29, 2007, 7:31 AM
    package empesec;
    import java.io.IOException;
    import javax.swing.*;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.JOptionPane;// Para el MessageDialog
    import javax.swing.event.*;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    * @author  Xavier Arroyo
    public class Main extends JFrame {
         * Creates new form Main
         int numCol;
        public Main() {
            initComponents();
         tResultado.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            setUpCategoryColumn(tResultado, tResultado.getColumnModel().getColumn(2));
            setUpSituationColumn(tResultado, tResultado.getColumnModel().getColumn(3));
            setUpDepartmentColumn(tResultado, tResultado.getColumnModel().getColumn(4));
            if (ALLOW_COLUMN_SELECTION) { // true by default
                if (ALLOW_ROW_SELECTION) {
                    //We allow both row and column selection, which
                    //implies that we *really* want to allow individual
                    //cell selection.
                    tResultado.setCellSelectionEnabled(true);
                tResultado.setColumnSelectionAllowed(true);
                ListSelectionModel colSM =
                    tResultado.getColumnModel().getSelectionModel();
                colSM.addListSelectionListener(new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent e) {
                        //Ignore extra messages.
                        if (e.getValueIsAdjusting()) return;
                        ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                        if (lsm.isSelectionEmpty()) {
                            return;
                        } else {
                            int selectedCol = lsm.getMinSelectionIndex();
                            //numCol = selectedCol;
                            /*System.out.println("Column " + selectedCol
                                               + " is now selected.");*/
                                if (ALLOW_ROW_SELECTION) { // true by default
                                    ListSelectionModel rowSM = tResultado.getSelectionModel();
                                    rowSM.addListSelectionListener(new ListSelectionListener() {
                                        public void valueChanged(ListSelectionEvent e) {
                                            //Ignore extra messages.
                                            if (e.getValueIsAdjusting()) return;
                                            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                                            if (lsm.isSelectionEmpty()) {
                                                System.out.println("");
                                            } else {
                                                int selectedRow = lsm.getMinSelectionIndex();
                                                tIdCompu.setText("ping wna-gye-" + modeloDef.getValueAt(selectedRow,0));
                                }else {
                                tResultado.setRowSelectionAllowed(false);
        /** 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.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            rbGroup = new javax.swing.ButtonGroup();
            jLabel1 = new javax.swing.JLabel();
            jSeparator1 = new javax.swing.JSeparator();
            textIdE = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            bOk = new javax.swing.JButton();
            bExit = new javax.swing.JButton();
            tJSPt = new javax.swing.JScrollPane();
            tResultado = new javax.swing.JTable();
            tIdCompu = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            bConnect = new javax.swing.JButton();
            rButton1 = new javax.swing.JRadioButton();
            rButton2 = new javax.swing.JRadioButton();
            bSave = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Consulta Activos Por Empleado");
            jLabel1.setText("Consulta de Activos por Empleados");
            jLabel2.setText("Id de Empleado :");
            bOk.setText("Aceptar");
            bOk.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    bOkMouseClicked(evt);
            bExit.setText("Borrar");
            bExit.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    bExitMouseClicked(evt);
         modeloDef = new javax.swing.table.DefaultTableModel(
              new Object [][] {
                new String [] {
                    "Codigo Barra", "Descripci?n", "Categor?a", "Situaci?n", "Departamento", "Nro. Modelo", "Nro. Serie", "Empresa", "Comentarios", "AR Number", "Sistema Operativo", "Version Office"
                boolean[] canEdit = new boolean [] {
                    false, true, true, true, true, true, true, true, true, true, true, true
         public boolean isCellEditable(int rowIndex, int columnIndex){
              return canEdit [columnIndex];
            tResultado.setModel(modeloDef);
            tJSPt.setViewportView(tResultado);
            jLabel3.setText("Command");
            bConnect.setText("Conectar");
            bConnect.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    bConnectMouseClicked(evt);
            rbGroup.add(rButton1);
            rButton1.setText("Por Apellido");
            rButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            rButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            rbGroup.add(rButton2);
            rButton2.setText("Por Nombre & Apellido");
            rButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            rButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
            bSave.setText("Guardar Cambios");
            bSave.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    bSaveMouseClicked(evt);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(tJSPt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
                        .add(layout.createSequentialGroup()
                            .add(253, 253, 253)
                            .add(jLabel1)))
                    .addContainerGap())
                .add(layout.createSequentialGroup()
                    .add(20, 20, 20)
                    .add(jLabel2)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(layout.createSequentialGroup()
                            .add(bOk)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(bExit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(textIdE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(rButton1)
                            .add(53, 53, 53)
                            .add(jLabel3))
                        .add(rButton2))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(tIdCompu, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 151, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(bConnect))
                    .add(87, 87, 87))
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(553, Short.MAX_VALUE)
                    .add(bSave)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jLabel1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel2)
                        .add(textIdE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(rButton1)
                        .add(tIdCompu, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jLabel3))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(bOk)
                            .add(bExit))
                        .add(bConnect)
                        .add(rButton2))
                    .add(23, 23, 23)
                    .add(tJSPt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 151, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(bSave)
                    .addContainerGap(27, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void bSaveMouseClicked(java.awt.event.MouseEvent evt) {                                  
    // TODO add your handling code here:
            tempDep.removeAllElements();
            tempCat.removeAllElements();
            tempSit.removeAllElements();
            actualizarDatos();
        private void bConnectMouseClicked(java.awt.event.MouseEvent evt) {                                     
            try {
    // TODO add your handling code here:
                //this.obtnerValue();
                int n = cmdPing();
                //new windowCmd(tIdCompu.getText()).setVisible(true);
                /*windowCmd ventanaPing = new windowCmd();
                ventanaPing.setTemp(tIdCompu.getText());
                ventanaPing.setearAreaTexto();
                ventanaPing.setVisible(true);*/
            } catch (Exception ex) {
                ex.printStackTrace();
        private void bExitMouseClicked(java.awt.event.MouseEvent evt) {                                  
    // TODO add your handling code here:
            limpiarTabla();
        private void bOkMouseClicked(java.awt.event.MouseEvent evt) {                                
    // TODO add your handling code here:
            if(bOk.isEnabled())
                this.bOk.setEnabled(false);
                obtenerEmpleado();
                mostrarDatos();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
        public void setUpCategoryColumn(JTable table, TableColumn categoryColumn) {
            JComboBox comboBox = new JComboBox();
            Connection conn = null;
            Conexion ejSQL = new Conexion();
            String consulta="";
            ResultSet rs=null;
            Vector vCombo = new Vector();
            if(ejSQL.conectar())
                try
                    conn = ejSQL.getConexion();//obtiene la conexion
                    consulta = "SELECT CategoriaActivo FROM Categorias_de_activo";
                    rs = ejSQL.ejecutarConsulta(consulta);
                    while(rs.next())
                        vCombo.addElement(rs.getString(1));
                    for(int i=0;i<vCombo.size();i++)
                        comboBox.addItem(vCombo.get(i));
                    categoryColumn.setCellEditor(new DefaultCellEditor(comboBox));
                    //Set up tool tips for the sport cells.
                    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                    renderer.setToolTipText("Click for combo box");
                    categoryColumn.setCellRenderer(renderer);
                    ejSQL.cerrarConexion();
                catch(SQLException e)
                        System.out.println("SQLException: " + e.getMessage());
                        while((e = e.getNextException()) != null)
                            System.out.println(e.getMessage());
         else
                System.out.println("Ha ocurrido un error con la base de datos");
        public void setUpSituationColumn(JTable table, TableColumn situationColumn) {
            JComboBox comboBox = new JComboBox();
            Connection conn = null;
            Conexion ejSQL = new Conexion();
            String consulta="";
            ResultSet rs=null;
            Vector vCombo = new Vector();
            if(ejSQL.conectar())
                try
                    conn = ejSQL.getConexion();//obtiene la conexion
                    consulta = "SELECT Situacion FROM Situacion";
                    rs = ejSQL.ejecutarConsulta(consulta);
                    while(rs.next())
                        vCombo.addElement(rs.getString(1));
                    for(int i=0;i<vCombo.size();i++)
                        comboBox.addItem(vCombo.get(i));
                    situationColumn.setCellEditor(new DefaultCellEditor(comboBox));
                    //Set up tool tips for the sport cells.
                    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                    renderer.setToolTipText("Click for combo box");
                    situationColumn.setCellRenderer(renderer);
                    ejSQL.cerrarConexion();
                catch(SQLException e)
                        System.out.println("SQLException: " + e.getMessage());
                        while((e = e.getNextException()) != null)
                            System.out.println(e.getMessage());
         else
                System.out.println("Ha ocurrido un error con la base de datos");
        public void setUpDepartmentColumn(JTable table, TableColumn departmentColumn) {
            JComboBox comboBox = new JComboBox();
            Connection conn = null;
            Conexion ejSQL = new Conexion();
            String consulta="";
            ResultSet rs=null;
            Vector vCombo = new Vector();
            if(ejSQL.conectar())
                try
                    conn = ejSQL.getConexion();//obtiene la conexion
                    consulta = "SELECT NombreDepartamento FROM Departamentos";
                    rs = ejSQL.ejecutarConsulta(consulta);
                    while(rs.next())
                        vCombo.addElement(rs.getString(1));
                    for(int i=0;i<vCombo.size();i++)
                        comboBox.addItem(vCombo.get(i));
                    departmentColumn.setCellEditor(new DefaultCellEditor(comboBox));
                    //Set up tool tips for the sport cells.
                    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                    renderer.setToolTipText("Click for combo box");
                    departmentColumn.setCellRenderer(renderer);
                    ejSQL.cerrarConexion();
                catch(SQLException e)
                        System.out.println("SQLException: " + e.getMessage());
                        while((e = e.getNextException()) != null)
                            System.out.println(e.getMessage());
         else
                System.out.println("Ha ocurrido un error con la base de datos");
        public void limpiarTabla(){
            this.bOk.setEnabled(true);
         this.textIdE.setText("");
            this.tIdCompu.setText("");
            int numFilas = this.tResultado.getRowCount();
            int numColumnas = this.tResultado.getColumnCount();
            vDepa.removeAllElements();
            vDescrip.removeAllElements();
            vSitua.removeAllElements();
            for(int i=0;i<numColumnas;i++)
                for(int j=0;j<numFilas;j++)
                    //modeloDef.setValueAt("",j,i);
                    modeloDef.removeRow(i);
            //System.out.println(numFilas + "+" + numColumnas);
            /*for(int i=0;i<numFilas;i++)
                System.out.println("borro " + i);
                modeloDef.removeRow(i);
                modeloDef.fireTableRowsDeleted(1,numFilas+1);
        public void obtenerEmpleado(){
            String nomEmpleado;
            nomEmpleado = textIdE.getText();
            if(rButton2.isSelected())
                obEmpleado.separarNombre(nomEmpleado);
                if (!obEmpleado.obtenerCodEmpleado()){
                    JOptionPane.showMessageDialog(null,"Usuario Incorrecto o No Existe!", "Mensaje!",JOptionPane.ERROR_MESSAGE);
                    textIdE.setText(null);
                    bOk.setEnabled(true);
            if(rButton1.isSelected())
        public int cmdPing() throws Exception
        Process p;
        int intResult;
        String strExec = new String(tIdCompu.getText());
        //p=Runtime.getRuntime().exec(strExec); // start the process
        p=Runtime.getRuntime().exec(strExec); // Modificar
        // now set something up that scans for output (independently)
        MGStreamGobbler mgSGErrors = new MGStreamGobbler(p.getErrorStream(),"error ");
        MGStreamGobbler mgSGOutput = new MGStreamGobbler(p.getInputStream(),"output ");
        // start the somethings
        mgSGErrors.start();
        mgSGOutput.start();
        // now wait for the actual process to end, wait for it's result
        intResult=p.waitFor();
        //String pruebaIP = mgSGOutput.extractIp();
        //tIdCompu.setText(pruebaIP);
        return(intResult);
       /**obtiene y ejecuta el CMD de Windows para poder obtener IP
        * de una computadora atraves del nombre de dicha maquina
        public void obtnerValue(){
                //tIdCompu.setText("ping -t wna-gye-"+obActivo.getIpCod());
            /*    Runtime r=Runtime.getRuntime (  ) ;
            try {
                Process P=r.exec(tIdCompu.getText());
            } catch (IOException ex) {
                ex.printStackTrace();
        public void mostrarDatos(){
        Connection conn = null;
        Conexion ejSQL = new Conexion();
        String consulta;
        int i=0, idEmpleado, cont = 0;
        ResultSet rs=null;
        idEmpleado = obEmpleado.getIdEmpleado();
            if(ejSQL.conectar())
                try
                    conn = ejSQL.getConexion();//obtiene la conexion
                    consulta = "SELECT act.Descripci?nActivo, cat.CategoriaActivo, sit.Situacion, dep.NombreDepartamento, act.N?mModelo, act.N?mSerie, act.C?digoDeBarras, act.Empresa, act.Comentarios_, act.Capital_Apropiation, act.Wd, act.Offi FROM Activos act, Categorias_de_Activo cat, Situacion sit, Departamentos dep WHERE act.IdEmpleado = "+idEmpleado+" And act.IdCategoriaActivo=cat.IdCategoriaActivo And act.IdSituacion = sit.IdSituacion And act.IdDepartamento=dep.IdDepartamento ORDER BY act.IdSituacion, act.IdCategoriaActivo";
                    //consulta = "SELECT DescripcionActivo FROM Activos";
                    rs = ejSQL.ejecutarConsulta(consulta);
                    while(rs.next())
                        vDescrip.addElement(rs.getString(1));
                        obActivo.setIdCategoria(rs.getString(2));
                        vSitua.addElement(rs.getString(3));
                        vDepa.addElement(rs.getString(4));
                        obActivo.setNumModelo(rs.getString(5));
                        obActivo.setNumSerie(rs.getString(6));
                        obActivo.setIdCodBarra(rs.getString(7));
                        obActivo.setEmpresa(rs.getString(8));
                        obActivo.setComentario(rs.getString(9));
                        obActivo.setArSerie(rs.getString(10));
                        obActivo.setOperativo(rs.getString(11));
                        obActivo.setOffice(rs.getString(12));
                        Object[] newRow={obActivo.getIdCodBarra(), vDescrip.get(i), obActivo.getIdCategoria(),
                        vSitua.get(i), vDepa.get(i), obActivo.getNumModelo(), obActivo.getNumSerie(),
                        obActivo.getEmpresa(), obActivo.getComentario(), obActivo.getArSerie(),
                        obActivo.getOperativo(), obActivo.getOffice()};
                        modeloDef.addRow(newRow);
                        i++;
                        cont++;
                    tResultado.updateUI();
                    ejSQL.cerrarConexion();
                catch(SQLException e)
                        System.out.println("SQLException: " + e.getMessage());
                        while((e = e.getNextException()) != null)
                            System.out.println(e.getMessage());
         else
                System.out.println("Ha ocurrido un error con la base de datos");
        public void actualizarDatos(){
            Connection conn = null;
            Conexion ejSQL = new Conexion();
            String consulta;
            //int i=0, idEmpleado, cont = 0;////////////
            ResultSet rs=null;
            //idEmpleado = obEmpleado.getIdEmpleado();//////////
            Vector tempCod = new Vector();
            Vector tempDes = new Vector();
            Vector tempMod = new Vector();
            Vector tempSer = new Vector();
            Vector tempEmp = new Vector();
            Vector tempCom = new Vector();
            Vector tempAR = new Vector();
            Vector tempOpe = new Vector();
            Vector tempOff = new Vector();
            int numFilas = this.tResultado.getRowCount();
            int numColumnas = this.tResultado.getColumnCount();
            for(int j=0;j<numFilas;j++)
                //System.out.println(numFilas +"+"+numColumnas);
                for(int k=0;k<numColumnas;k++)
                    //modeloDef.removeRow(j);
                    //System.out.println(modeloDef.getValueAt(j,k));
                    if(modeloDef.getValueAt(j,k)==null)
                        modeloDef.setValueAt("  ",j,k);
                    switch(k)
                        case 0:
                            tempCod.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempCod.lastElement());
                            break;
                        case 1:
                            tempDes.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempDes.lastElement());
                            break;
                        case 2:
                            tempCat.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempCat.lastElement());
                            break;
                        case 3:
                            tempSit.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempSit.lastElement());
                            break;
                        case 4:
                            tempDep.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempDep.lastElement());
                            break;
                        case 5:
                            tempMod.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempMod.lastElement());
                            break;
                        case 6:
                            tempSer.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempSer.lastElement());
                            break;
                        case 7:
                            tempEmp.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempEmp.lastElement());
                            break;
                        case 8:
                            tempCom.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempCom.lastElement());
                            break;
                        case 9:
                            tempAR.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempAR.lastElement());
                            break;
                        case 10:
                            tempOpe.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempOpe.lastElement());
                            break;
                        case 11:
                            tempOff.addElement(modeloDef.getValueAt(j,k));
                            //System.out.println(tempOff.lastElement());
                            break;
            actualizarDepartamento();
            actualizarCategoria();
            actualizarSituacion();
            if(ejSQL.conectar())
                try
                    conn = ejSQL.getConexion();//obtiene la conexion
                    for(int i=0;i<tempDep.size();i++ )
                        System.out.println(tempOff.get(i));
                        consulta = "UPDATE Activos SET Descripci?nActivo='"+tempDes.get(i)+"'  WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempMod.size();i++ )
                        consulta = "UPDATE Activos SET N?mModelo='"+tempMod.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempSer.size();i++ )
                        consulta = "UPDATE Activos SET N?mSerie='"+tempSer.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempEmp.size();i++ )
                        consulta = "UPDATE Activos SET Empresa='"+tempEmp.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempCom.size();i++ )
                        consulta = "UPDATE Activos SET Comentarios_='"+tempCom.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempAR.size();i++ )
                        consulta = "UPDATE Activos SET Capital_Apropiation='"+tempAR.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempOpe.size();i++ )
                        consulta = "UPDATE Activos SET Wd='"+tempOpe.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                    for(int i=0;i<tempOff.size();i++ )
                        consulta = "UPDATE Activos SET Offi='"+tempOff.get(i)+"' WHERE C?digoDeBarras = '"+tempCod.get(i)+"'";                  
                        rs = ejSQL.ejecutarConsulta(consulta);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

    Hi
    Not sure what the use case is here but what I would do is to make sure when you create the employee or whatever the salary gets initialised to 0, db trigger, default etc.
    instead of null (null values can be a PITA when you have to search on them)
    Then all you have to do is to force a numeric input, the user can type 0 for all unassigned salaries.
    This removes the problem you have of leaving the box blank and having to accept the word NULL as an input value.
    HTH
    Paul

  • JTable - JComboBox/List - JTable

    My target: I would like to have multiple columns in my comboBox or list. When I choose one item, the result would be just a single column but not all columns. Moreover, the whole comboBox is actually one cell within a JTable. i.e. when I click one cell of a jtable, it shows a comboBox.
    I have searched this forum but just found some ways to get multiple columns in comboBox, and it seem no one has tried to include it in a JTable cell. I just wonder if anyone can help and it would be thankful.

    Let me post the code here:
    //the init of comboBox model within jtable here
         private void initSupplierCombo(TableColumn col){
           String query = "select supplier_no, supplier_name from supplier_master group by supplier_no,supplier_name;";
           JComboBox comboBox = new JComboBox();
           Vector supplierList = itemDB.getComboResults(query);
           try {
             comboBox.setModel(new ResultSetComboBoxModel(supplierList));
             col.setCellEditor(new DefaultCellEditor(comboBox));
             DefaultTableCellRenderer renderer =
                 new DefaultTableCellRenderer();
             renderer.setToolTipText(
                 "Click for combo box & choose");
             col.setCellRenderer(renderer);
             //Set up tool tip for the sport column header.
             TableCellRenderer headerRenderer = col.getHeaderRenderer();
             if (headerRenderer instanceof DefaultTableCellRenderer) {
               ( (DefaultTableCellRenderer) headerRenderer).setToolTipText(
                   "Click to see a list of choices");
           catch (Exception e) {
             e.printStackTrace();
    //ResultSetComboBoxModel
    import javax.swing.*;
    import java.sql.*;
    import java.util.Vector;
    public class ResultSetComboBoxModel extends ResultSetListModel
        implements ComboBoxModel
        protected Object selected = null;
        public ResultSetComboBoxModel(Vector columnResults) throws Exception {
            super(columnResults);
        public Object getSelectedItem() {
          return selected;
        public void setSelectedItem(Object o) {
            if(o==null)
              selected = o;
            else{
              String value = (String) o;
              selected = (Object)(value.substring(0,value.lastIndexOf("  //  ")));
    //ResultSetListModel
    import javax.swing.*;
    import java.util.*;
    import java.sql.*;
    public class ResultSetListModel extends AbstractListModel {
        List values = new ArrayList();
        public ResultSetListModel(Vector columnResults) throws Exception {
          for(Iterator item = columnResults.iterator();item.hasNext();){
            String[] value  = (String[])item.next();
            values.add(value[0] + "  //  " + value[1]);
        public int getSize() {
            return values.size();
        public Object getElementAt(int index) {
          return values.get(index);
    }

  • JTable blues

    Hello, I am having a hard time getting my JTable to show up on my panel. There is a fair bit of code to wade through so I have put comments in all CAPS lined with an '*' so it should be easy to find where I am having my problems.
    What I would like to do is have a new table row added each time the user enters a service and clicks a button. A service name and an integer for the durration of the service. Additonaly the opposite when the remove service button is clicked.
    When running the app, click the employees tab; there is a NullPointerException error right now with the line
    return getValueAt(0, c).getClass(); at line 904 once that tab is clicked.
    Things to look for in my code are:
    -westPanel
    -westRight
    -table
    -MyTableModel
    -scrollpane2
    -(maybe servicePanel) undecided and it is commented out at this moment.
    Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.
    Thanks in advance.
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.plaf.metal.MetalLookAndFeel;
    import javax.swing.table.AbstractTableModel;
    public class Administration extends JFrame implements ActionListener,ListSelectionListener,ItemListener {
         private JTabbedPane      jtp;
         public String[] columnNames;
         public Object[][] data;
         public static JPanel     servicePanel;
         public static int          checkRow;
         private JPanel                westPanel;
         private JPanel                westTop;
         private JPanel                westCenter;
         private JPanel                westCenterTop;
         private JPanel                westCenterBottom;
         private JPanel                westBottom;
         private JPanel               westBottomRight;
         private JPanel               westLeft;
         private JPanel               westRightTop;
         private JPanel               westRight;
         private JPanel                northPanel;
         private JPanel               centerPanel;
         private JPanel                centerRight;
         private JPanel               centerLeft;
         private JPanel                eastPanel;
         private JPanel                eastRight;
         private JPanel                eastLeft;
         private JPanel                eastBottom;
         public static JPanel               eastEastTop;
         private JPanel               eastEastCenter;
         private JPanel                southPanel;
         private JPanel                southTop;
         private JPanel                southLeft;
         private JPanel                southCenter;
         private JPanel                southBottom;
         private GridBagLayout      gbl;
         private GridBagConstraints gbc;
         //private JComboBox      employees;
         private JComboBox[]      openAmPm = new JComboBox[7];
         private JComboBox[]      closedAmPm = new JComboBox[7];
         private JComboBox     startAmPm;
         private JComboBox     endAmPm;
         private JComboBox      cmbServices;
         private JList          employees;
         private JList           listEmpl;
         private JList           listServices;
         private JList          listDays;
         private JList          listSchedule;
         //private Vector           nameData;
         private JScrollPane      scrollpane;
         private JScrollPane          scrollpane2;
         private JScrollPane      scrollPane3;
         private JScrollPane          scrollPane4;
         private JLabel           lblEmployees;
         public static JLabel          lblEmployeeName;
         public static JLabel      lblMonthStat;
         public static JLabel          lblDay;
         public static JLabel           lblYear;
         public static String service = null;
         private JLabel          lblLength;
         private JLabel           lblBizHours;
         private JLabel           lblServices;
         private JLabel          lblHoliday;
         private JLabel           lblOpen;
         private JLabel           lblClosed;
         private JLabel           lblsouthHeading;
         private JLabel           lblStartTime;
         private JLabel           lblEndTime;
         private JLabel          lblDayOff;
         private JLabel          space;
         private JLabel          space2;
         private JLabel           space3;
         private JLabel           space4;
         private JLabel          space5;
         private JLabel          blank1;
         private JLabel          blank2;
         private JLabel           colon;
         private JLabel           colon2;
         private JLabel      lblSelect;
         private JLabel[] weekDay =new JLabel[7];
         //private String[] fakeName = {"Leon","Mike","Lori","Shannon","Rob"};
         private final static String[] dow = {"Sunday",
                                  "Monday",
                                  "Tuesday",
                                     "Wednesday",
                                  "Thursday",
                                  "Friday",
                                     "Saturday"};
         public static JTextField[]      startHr = new JTextField[7];
         public static JTextField[]      startMin = new JTextField[7];
         public static JTextField[]     finishHr = new JTextField[7];
         public static JTextField[]     finishMin = new JTextField[7];
         private JButton[]      btnUpdate = new JButton[7];
         private JButton          btnAddEmployee;
         private JButton         btnNextDay;
         private DefaultListModel nameData;
         private DefaultListModel serviceData;
         private DefaultListModel dayData;
         private DefaultListModel holidayData;
         private DefaultListModel scheduleData;
         private static final String hireString="Add Employee";
         private static final String fireString="Remove Employee";
         private static final String addService="Add Service";
         private static final String removeService="Remove Service";
         private JButton fireButton;
         private JButton hireButton;
         private JButton addServices;
         private JButton removeServices;
         private JButton btnAttatch;
         private JTextField employeeName;
         private JTextField serviceName;
         private JTextField txtOpenTime;
         private JTextField txtClosedTime;
         private int size;
         public static String timeText;
         private boolean result;
         private boolean totalResult;
         private String holidayMsg = "Here, you can select and \n schedule off days \n for employees from \n the list";
         private String message1 = "Enter a maximum of \n 3 digits";
         private String message2 = "Enter numbers only";
         private String minutes=" min";
         private String name;
         private boolean dbRecord=true;
         private int serviceSize;
         private JCheckBox[] dayOff = new JCheckBox[7];
         private int jlistCellWidth =100;
         public static final int MAX_CHARS = 1;
         private String myMonth;
         public static boolean removed=false;
         public Administration()
              //jtp.setDefaultLookAndFeelDecorated(true);
              checkRow = 0;
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              gbl = new GridBagLayout();
              gbc = new GridBagConstraints();
              //employees = new JComboBox();
              //employees.setEditable(false);
              cmbServices = new JComboBox();
              startAmPm = new JComboBox();
              startAmPm.addItem("AM");
              startAmPm.addItem("PM");
              startAmPm.setEditable(false);
              endAmPm = new JComboBox();
              endAmPm.addItem("AM");
              endAmPm.addItem("PM");
              endAmPm.setEditable(false);
              employeeName=new JTextField("",10);
              serviceName = new JTextField("",10);
              txtOpenTime = new JTextField("",5);
              txtClosedTime = new JTextField("",5);
              nameData = new DefaultListModel();
              holidayData = new DefaultListModel();
    /**     Eventualy put this into an isItemSelected function that retrieves names from
    *     the database
              /*nameData.addElement("Leon");
              nameData.addElement("Brenda");
              nameData.addElement("Megumi");
              nameData.addElement("jun");
              //populate employee combobox with names from nameData
              //int listSize = nameData.getSize();
         /*     for(int i=0;i<fakeName.length;i++)
                   nameData.addElement(fakeName);
                   //listEmpl.setSelectedIndex(i);
                   //String eName =(String)nameData.get(listEmpl.getSelectedIndex());
                   holidayData.addElement(fakeName[i]);
              serviceData = new DefaultListModel();
              dayData = new DefaultListModel();
              listEmpl=new JList(nameData);
              listEmpl.addListSelectionListener(this);
              listServices = new JList(serviceData);
              employees = new JList(holidayData);
              employees.addListSelectionListener(this);
              employees.setFixedCellWidth(jlistCellWidth);
              listDays = new JList(dayData);
              scheduleData = new DefaultListModel();
              listSchedule = new JList(scheduleData);
              listSchedule.setFixedCellWidth(jlistCellWidth);
              dayData.addElement("Sunday");
              dayData.addElement("Monday");
              dayData.addElement("Tuesday");
              dayData.addElement("Wednesday");
              dayData.addElement("Thursday");
              dayData.addElement("Friday");
              dayData.addElement("Saturday");
         //     listEmpl.setSelectedIndex(0);
              listDays.setSelectedIndex(0);
              listSchedule.setSelectedIndex(0);
              //listEmpl.addListSelectionListener(this);
              listEmpl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              listDays.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              employees.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              size = nameData.getSize();
              //employeeName.setText("size is "+size);
              listEmpl.setVisibleRowCount(5);
              listDays.setVisibleRowCount(7);
              employees.setVisibleRowCount(5);
              listSchedule.setVisibleRowCount(5);
              gbc.fill=GridBagConstraints.HORIZONTAL;
              gbc.anchor=GridBagConstraints.CENTER;
                   //declare labels
                        lblLength = new JLabel("SERVICE LENGTH",lblLength.CENTER);
                        lblSelect=new JLabel("Select a name from the list",lblSelect.CENTER);
                        lblsouthHeading = new JLabel("EMPLOYEE SCHEDULE",lblsouthHeading.CENTER);
                        lblEmployees = new JLabel("CURRENT EMPLOYEES",lblEmployees.CENTER);
                        lblEmployees.setOpaque(true);
                        //lblEmployees.setBackground(Color.yellow);
                        lblServices = new JLabel("CURRENT SERVICES",JLabel.LEFT);
                        lblBizHours= new JLabel("BUSINESS HOURS",lblBizHours.CENTER);
                        lblStartTime = new JLabel("Open",lblStartTime.LEFT);
                        lblEndTime = new JLabel("Closed",lblEndTime.LEFT);
                        blank1 = new JLabel("");
                        blank2=new JLabel("");
                        lblHoliday = new JLabel(holidayMsg);
                        lblEmployeeName = new JLabel("Name");
                        //lblEmployeeName.setForeground(Color.white);
                        lblMonthStat = new JLabel("");
                        lblDay = new JLabel("");
                        lblYear = new JLabel("");
                        //check myCalendar method to see if a button has been clicked
                        lblMonthStat.setForeground(Color.white);
                        lblDay.setForeground(Color.white);
                        lblYear.setForeground(Color.white);
              //declare buttons
              JButton btnAttatch = new JButton("<html>Attatch service<br> to employee</html>");
              btnAttatch.setBorder(BorderFactory.createRaisedBevelBorder());
              JButton fireButton = new JButton(fireString);
              JButton hireButton = new JButton(hireString);
              JButton addServices = new JButton(addService);
              JButton removeServices = new JButton(removeService);
              addServices.addActionListener(this);
              addServices.setActionCommand(addService);
              removeServices.addActionListener(this);
              removeServices.setActionCommand(removeService);
              hireButton.addActionListener(this);
              fireButton.setActionCommand(fireString);
              fireButton.addActionListener(this);
              JButton btnAddEmployee = new JButton("Add Employee");
              fireButton.setBorder(BorderFactory.createRaisedBevelBorder());
              JButton btnServices = new JButton("Add Service");
              addServices.setBorder(BorderFactory.createRaisedBevelBorder());
              removeServices.setBorder(BorderFactory.createRaisedBevelBorder());
              hireButton.setBorder(BorderFactory.createRaisedBevelBorder());
              //declare layouts
              BorderLayout southBorder = new BorderLayout();
              FlowLayout flo = new FlowLayout(FlowLayout.CENTER,30,30);
              FlowLayout westFlo = new FlowLayout(FlowLayout.CENTER,10,10);
              FlowLayout southFlo = new FlowLayout(FlowLayout.LEFT,10,10);
              GridLayout northGrid = new GridLayout(0,4);
              GridLayout southGrid = new GridLayout(1,1);
              GridLayout westGrid = new GridLayout(1,2);
              GridLayout southRow1 = new GridLayout(1,1,10,10);
              GridLayout southRow2 = new GridLayout(2,0,10,10);
              GridLayout eastGrid = new GridLayout(0,2,10,10);
              //declare panels
              servicePanel=new JPanel();
              servicePanel.setLayout(new GridLayout(0,2));
              //servicePanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
              servicePanel.setPreferredSize(new Dimension(100,0));
              westPanel = new JPanel();
              westTop = new JPanel();
              westCenter = new JPanel();
              westBottomRight= new JPanel();
              westCenterBottom = new JPanel();
              westBottom = new JPanel();
              westLeft = new JPanel();
              westRightTop = new JPanel();
              westRight = new JPanel();
              northPanel = new JPanel();
              centerPanel = new JPanel();
              centerRight = new JPanel();
              centerLeft = new JPanel();
              eastPanel=new JPanel();
              eastRight = new JPanel();
              eastLeft = new JPanel();
              eastBottom = new JPanel();
              eastEastTop = new JPanel();
              eastEastCenter = new JPanel();
              southPanel = new JPanel();
              southTop = new JPanel();
              southLeft = new JPanel();
              southCenter = new JPanel();
              southBottom = new JPanel();
              /////////////////set the panels/////////////////////
              //NORTH
              northPanel.setLayout(flo);
              //northPanel.setBackground(Color.cyan);
              //WEST
              westPanel.setLayout(westGrid);
              westPanel.setBorder(BorderFactory.createEtchedBorder());
              westTop.setLayout(new GridLayout(2,1));
              westTop.setBorder(BorderFactory.createEtchedBorder());
              westCenter.setBorder(BorderFactory.createRaisedBevelBorder());
              westCenter.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
              westBottom.setLayout(new GridLayout(3,3,10,10));
              westLeft.setLayout(new GridLayout(0,1));
              //westRightTop.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
              westRightTop.setLayout(new GridLayout(0,2));
              westRight.setLayout(new GridLayout(1,1));
              //westBottom.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
              //westBottom.setLayout(new GridLayout(2,2,20,20));
              //CENTER
              centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
              centerRight.setLayout(gbl);
              centerRight.setPreferredSize(new Dimension(500,200));
              centerRight.setBorder(BorderFactory.createRaisedBevelBorder());
              //EAST
              eastPanel.setLayout(eastGrid);
              eastRight.setLayout(new GridLayout(1,1));
              eastEastTop.setLayout(new FlowLayout(FlowLayout.LEFT));
              eastEastCenter.setLayout(new FlowLayout(FlowLayout.CENTER));
              eastPanel.setBorder(BorderFactory.createEtchedBorder());
              //SOUTH
              southPanel.setBorder(BorderFactory.createRaisedBevelBorder());
              southPanel.setLayout(southBorder);
              southPanel.setPreferredSize(new Dimension(0,227));
              southTop.setLayout(westGrid);
              southLeft.setLayout(southGrid);
              southLeft.setPreferredSize(new Dimension(70,0));
              //southLeft.setBorder(BorderFactory.createRaisedBevelBorder());
              //southRight.setLayout(westGrid);
              southCenter.setLayout(southFlo);
              southCenter.setPreferredSize(new Dimension(100,200));
              southCenter.setBorder(BorderFactory.createRaisedBevelBorder());
              //add to scrolling pane
              scrollpane = new JScrollPane(employees);
              scrollpane.getViewport().add(employees);
              CREATING AN INSTANCE OF JTABLE
              JTable table = new JTable(new MyTableModel());
              table.setPreferredScrollableViewportSize(new Dimension(200,200));
              ADDING THE TABLE TO THE SCROLLPANE2
              scrollpane2 = new JScrollPane(table);
              //scrollpane2.getViewport().add(servicePanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scrollPane3 = new JScrollPane(listEmpl);
              scrollPane3.getViewport().add(listEmpl);
              scrollPane4 = new JScrollPane(listSchedule);
              scrollPane4.getViewport().add(listSchedule);
              //get the content pane
              Container pane = getContentPane();
              JPanel calendars = new JPanel(new GridLayout(0,1));
              JScrollPane jsp = new JScrollPane(calendars);
              GregorianCalendar gc = new GregorianCalendar();
              //gc.set(GregorianCalendar.DAY_OF_YEAR,1);
              gc.set(GregorianCalendar.DAY_OF_MONTH,1);
         for (int i=0; i<12; i++)
         calendars.add(new CalendarPanel(gc,this));
         gc.add(GregorianCalendar.MONTH, 1);
              cmbServices.setEditable(true);
              //add components to the panels
              northPanel.add(lblsouthHeading);
              westTop.add(lblEmployees);
              westTop.add(scrollpane);
              westCenter.add(hireButton);
              westCenter.add(employeeName);
              westCenter.add(fireButton);
              westCenter.add(addServices);
              westCenter.add(serviceName);
              westCenter.add(removeServices);
              westLeft.add(westTop);
              westLeft.add(westCenter);
         ADDING THE SCROLLPANE2 WHICH HOLDS
         JTABLE TO THE WESTRIGHT PANEL
         THEN FINALY TO THE WESTPANEL
              westRight.add(scrollpane2);
              westRight.add(new JLabel("TEST"));
              westPanel.add(westLeft);
              westPanel.add(westRight);
              //westPanel.add(westCenter);
              //westPanel.add(westBottom,BorderLayout.SOUTH);
              westPanel.setBorder(BorderFactory.createRaisedBevelBorder());
              eastLeft.add(lblSelect);
              eastLeft.add(scrollPane3);
              eastRight.add(eastLeft,BorderLayout.CENTER);
              eastRight.add(jsp,BorderLayout.EAST);
              //eastEastTop.add(lblEmployeeName);
              //eastEastTop.setBackground(Color.black);
              //eastEastTop.add(lblMonthStat);
              eastEastTop.add(lblDay);
              eastEastTop.add(lblYear);
              eastPanel.add(eastRight,BorderLayout.CENTER);
              eastPanel.add(eastEastTop);
              //eastPanel.add(eastEastCenter);
              //eastPanel.add(eastBottom,BorderLayout.SOUTH);
              southTop.add(lblBizHours);
              //southLeft.add(scrollpane);
              southLeft.add(listDays);
              southCenter.add(lblStartTime);
              southCenter.add(txtOpenTime);
              southCenter.add(startAmPm);
              southCenter.add(lblEndTime);
              southCenter.add(txtClosedTime);
              southBottom.add(btnNextDay = new JButton("Next Day"));
              southCenter.add(endAmPm);
              southPanel.add(southTop,BorderLayout.NORTH);
              southPanel.add(southLeft,BorderLayout.WEST);
              southPanel.add(southCenter,BorderLayout.CENTER);
              //southPanel.add(jsp,BorderLayout.EAST);
              southPanel.add(southBottom,BorderLayout.SOUTH);
              int row =1;
              lblOpen = new JLabel("Start Time",lblOpen.RIGHT);
              lblClosed = new JLabel("Quiting Time",lblClosed.RIGHT);
              lblDayOff = new JLabel("Day Off");
              space5 = new JLabel();
              centerLeft.add(lblEmployeeName);
              addComp(centerRight,lblDayOff,gbl,gbc,0,5,1,1,1,1);
              for(int i=0;i<dow.length;i++){
                   weekDay[i]= new JLabel(""+dow[i],weekDay[i].LEFT);
                   colon = new JLabel(":",colon.CENTER);
                   colon2 = new JLabel(":",colon2.CENTER);
                   weekDay[i].setForeground(Color.red);
                   startHr[i] = new JTextField("",1);
                   keyListener kl=new keyListener();
                   startHr[i].addKeyListener(kl);
                   startMin[i] = new JTextField("",1);
                   startMin[i].addKeyListener(kl);
                   finishHr[i] = new JTextField("",1);
                   finishHr[i].addKeyListener(kl);
                   finishMin[i] = new JTextField("",1);
                   finishMin[i].addKeyListener(kl);
                   btnUpdate[i] = new JButton("Update");
                   dayOff[i] = new JCheckBox();
                   dayOff[i].addItemListener(this);
                   space = new JLabel();
                   space2 = new JLabel();
                   space3 = new JLabel();
                   space4 = new JLabel();
                   btnUpdate[i].setBorder(BorderFactory.createRaisedBevelBorder());
                   //lblOpen = new JLabel("Shift Start",lblOpen.RIGHT);
                   //lblClosed = new JLabel("Shift End",lblClosed.RIGHT);
                   openAmPm[i] = new JComboBox();
                   closedAmPm[i] = new JComboBox();
                   openAmPm[i].addItem("AM");
                   openAmPm[i].addItem("PM");
                   closedAmPm[i].addItem("AM");
                   closedAmPm[i].addItem("PM");
                   addComp(centerRight,space,gbl,gbc,row,2,1,1,1,1);
                   addComp(centerRight,weekDay[i],gbl,gbc,row,3,1,1,1,1);
                   addComp(centerRight,space3,gbl,gbc,row,4,1,1,1,1);
                   addComp(centerRight,dayOff[i],gbl,gbc,row,5,1,1,1,1);
                   //addComp(centerRight,lblOpen,gbl,gbc,row,6,1,1,1,1);
                   addComp(centerRight,startHr[i],gbl,gbc,row,7,1,1,1,1);
                   addComp(centerRight,colon,gbl,gbc,row,8,1,1,1,1);
                   addComp(centerRight,startMin[i],gbl,gbc,row,9,1,1,1,1);
                   addComp(centerRight,openAmPm[i],gbl,gbc,row,10,1,1,1,1);
                   //addComp(centerRight,lblClosed,gbl,gbc,row,11,1,1,1,1);
                   addComp(centerRight,finishHr[i],gbl,gbc,row,12,1,1,1,1);
                   addComp(centerRight,colon2,gbl,gbc,row,13,1,1,1,1);
                   addComp(centerRight,finishMin[i],gbl,gbc,row,14,1,1,1,1);
                   addComp(centerRight,closedAmPm[i],gbl,gbc,row,15,1,1,1,1);
                   addComp(centerRight,space4,gbl,gbc,row,16,1,1,1,1);
                   addComp(centerRight,btnUpdate[i],gbl,gbc,row,17,1,1,1,1);
                   addComp(centerRight,space2,gbl,gbc,row,18,1,1,1,1);
                   row++;
              }//end for loop
              //add the panels
              //pane.add(northPanel,BorderLayout.NORTH);
              //pane.add(centerRight,BorderLayout.CENTER);
              //pane.add(westPanel,BorderLayout.WEST);
         //     pane.add(eastPanel,BorderLayout.EAST);
         //     pane.add(southPanel,BorderLayout.SOUTH);
              centerPanel.add(centerLeft);
              centerPanel.add(centerRight);
              //set up tabbed pane
              jtp = new JTabbedPane();
              jtp.addTab("Schedule",centerPanel);
              jtp.addTab("Employees",westPanel);
              jtp.addTab("Holidays",eastPanel);
              jtp.addTab("Business Hours",southPanel);
              pane.add(jtp,BorderLayout.CENTER);
         }//end init
         private void addComp(JPanel panel,Component c,GridBagLayout gbl,
                        GridBagConstraints gbc, int row,
                        int column, int numRows, int numColumns,
                        int weightx, int weighty)
                   gbc.gridy = row;
                   gbc.gridx = column;
                   gbc.gridheight = numRows;
                   gbc.gridwidth = numColumns;
                   gbc.weightx = weightx;
                   gbc.weighty = weighty;
                   //set the constraints in the GridBagLayout
                   gbl.setConstraints(c,gbc);
                   panel.add(c);
              }//end addcomp
         public void actionPerformed(ActionEvent e)
              //This method can be called only if
              //there's a valid selection
              int intLength;
              String command=e.getActionCommand();
              int listIndex1 = listEmpl.getSelectedIndex();
              int listIndex2 = listServices.getSelectedIndex();
              String firstName=null;
              //String service=null;
              if(command.equals("Add Employee"))
                   firstName = employeeName.getText();
                   //employeeName.setText(""+index);
                   //User didn't type in a unique name...
                   if (firstName.equals("") || alreadyInList(nameData,firstName))
                        Toolkit.getDefaultToolkit().beep();
                        employeeName.requestFocusInWindow();
                        employeeName.selectAll();
                        return;
                   }//end if
                   //int index = listEmpl.getSelectedIndex();
                   //get selected index
                   //if (listIndex1 == -1)
                        //no selection, so insert at beginning
                        //listIndex1 = 0;
                        //employeeName.setText("listIndex=-1");
                   //}//end if
                   else
                        //add after the selected item
                        //promptServices();
                        nameData.addElement(firstName);
                        size=nameData.getSize();
                        //fill the employee combobox
                        //employees.addItem(firstName);
                        holidayData.addElement(firstName);
                        listIndex1++;
                        employeeName.setText("size is "+size);
                        //Reset the text field.
                        employeeName.requestFocusInWindow();
                        employeeName.setText("");
                        scrollpane.revalidate();
                        scrollpane.repaint();
              }//end if
              if(command.equals("Remove Employee"))
                   nameData.remove(listIndex1);
                   holidayData.remove(listIndex1);
                   //removed item in last position
                   listIndex1--;
                   size = nameData.getSize();
                   employeeName.setText("size is "+size);
                   if (size==0)
                        //Nobody's left, disable firing.
                        fireButton.setEnabled(false);
                   }//end if
                   else
                   //Select an index.
                   if (listIndex1 == nameData.getSize())
                        listEmpl.setSelectedIndex(listIndex1);
                        listEmpl.ensureIndexIsVisible(listIndex1);
                   }//end if
              }//end if
              HERE IS WHERE A NEW ROW WITH A SERVICE AND DURRATION SHOULD BE ADDED TO THE JTABLE
              EACH TIME THE BUTTON IS CLICKED
              if(command.equals("Add Service"))
                        service=serviceName.getText();
                        if (service.equals("") || alreadyInList(serviceData,service))
                             Toolkit.getDefaultToolkit().beep();
                             serviceName.requestFocusInWindow();
                             serviceName.selectAll();
                             return;
                        }//end if
                        else
                             do{
                             timeText = JOptionPane.showInputDialog(listServices, "Enter the time allowed in minutes for \n a "+service+ " appointment");
                             totalResult=validateInputBox(timeText);
                             }while(!totalResult);
                             repaint();
                             //add after the selected item
                             //serviceData.addElement(service+" "+ timeText+ minutes);
                             //cmbServices.addItem(service);
                             serviceName.requestFocusInWindow();
                             serviceName.setText("");
                             listIndex2++;
                             //scrollpane.revalidate();
                             //scrollpane.repaint();
                             scrollpane2.revalidate();
                             scrollpane2.repaint();
                             //int time = Integer.parseInt(timeText);
                   }//end else
              }//end if
         /*     else if(command.equals("Remove Service"))
                   System.out.println("Selected:"+CheckServices.selected);
                   if(CheckServices.selected){
                        //for(int i=0;i<
                        servicePanel.remove(CheckServices.newChk);
                        servicePanel.remove(CheckServices.lengthLbl);
                        repaint();
                   int index = listEmpl.getSelectedIndex();
                   serviceData.remove(listIndex2);
                   //removed item in last position
                   listIndex2--;
                   size = serviceData.getSize();
                   //employeeName.setText("size is "+size);
                   if (size == 0)
                        //Nobody's left, disable firing.
                        removeServices.setEnabled(false);
                   }//end if
                   else
                   //Select an index.
                   if (listIndex2 == serviceData.getSize())
                        listServices.setSelectedIndex(listIndex2);
                        listServices.ensureIndexIsVisible(listIndex2);
                   }//end if
              }//end if
              //Select the new item and make it visible.
              //listEmpl.setSelectedIndex(listIndex1);
              //listEmpl.ensureIndexIsVisible(listIndex1);
              //listServices.ensureIndexIsVisible(listIndex2);
              //listServices.setSelectedIndex(listIndex2);
         }//end actionperformed
         public void itemStateChanged(ItemEvent e)
              boolean selected=false;
              int status = e.getStateChange();
              if(status==ItemEvent.SELECTED)
                   for(int i=0;i<dayOff.length;i++)
                        if(dayOff[i].isSelected())
                             int index = i;
                             startHr[i].setEditable(false);
                             startHr[i].setText("DAY OFF");
                             startMin[i].setEditable(false);
                             finishHr[i].setEditable(false);
                             finishMin[i].setEditable(false);
                        }//end if
                   }//end for
              }//end if
              if(status==ItemEvent.DESELECTED)
                   for(int i = 0;i<dayOff.length;i++)
                        if(!dayOff[i].isSelected())
                             startHr[i].setEditable(true);
                             startMin[i].setEditable(true);
                             finishHr[i].setEditable(true);
                             finishMin[i].setEditable(true);
                        }//end if
                   }//end for
              }//end if
         public boolean validateInputBox(String t)
              result=false;
              int intLength= t.length();
              if(intLength <=3)
                   for(int i = 0;i<intLength;i++)
                        if(!Character.isDigit(timeText.charAt(i)))
                             JOptionPane.showMessageDialog(listServices,message2 );
                             return result;
                             //break;
                   result=true;
                   return result;
              }//end if
              else{
              JOptionPane.showMessageDialog(listServices,message1 );
              return result;
         }//end validate method
              //This method tests for string equality. You could certainly
              //get more sophisticated about the algorithm. For example,
              //you might want to ignore white space and capitalization.
              protected boolean alreadyInList(DefaultListModel myList,String name)
                   return myList.contains(name);
         //handler for list selection changes
         public void valueChanged(ListSelectionEvent event)
              if(event.getSource()==listEmpl && !event.getValueIsAdjusting())
                   /**Load up any relating service information from the database
                   for the selected employee. If there is no record then reset the
                   serviceData list to empty so new services can be added
                   if(dbRecord){
                        serviceData.addElement("Record added");
                        dbRecord=false;
                   else
                        serviceData.clear();
              }//end if
              if(event.getSource()==employees ||event.getSource()==listEmpl && !event.getValueIsAdjusting()){
                   System.out.println("value changed");
                   int index = employees.getSelectedIndex();
                   Object item =employees.getModel().getElementAt(index);
                   lblEmployeeName.setText((String)item);
                   //lblEmployeeName.setText("Changed");
                   //centerLeft.add(lblEmployeeName);
         }//end valueChanged
         public void promptServices()
              JOptionPane.showMessageDialog(employees,"Enter a service");
    HERE IS THE MYTABLEMODEL CLASS. NOTE:ELEMENT INTEGER(5) WILL BE REPLACED
    WITH THE VARIABLE TIMETEXT BECAUSE THIS ELEMENT IS USER DEFINED BUT
    DOING SO RIGHT NOW THROWS AN ERROR
    class MyTableModel extends AbstractTableModel{
                   String columnNames[] = {"Service", "Minutes", "Select"};
                   Object data[][] = { {service, new Integer(5), new Boolean(false)} };
                        public int getColumnCount()
                             return columnNames.length;
                        public int getRowCount()
                             return data.length;
                        public String getColumnName(int col)
                             return columnNames[col];
                        public Object getValueAt(int row, int col)
                             return data[row][col];
              /* * JTable uses this method to determine the default renderer
                        / * editor for each cell. If we didn't implement this method,
                        * then the last column would contain text ("true"/"false"),
                        * rather than a check box. */
         public Class getColumnClass(int c)
                   THIS LINE IS THROWING A NULLPOINTEREXCEPTION ERROR
                   return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
              System.out.println("hey hey hey");
    //Note that the data/cell address is constant
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    //public void setValueAt(Object value, int row, int col) {
    // data[row][col] = value;
    // fireTableCellUpdated(row, col);
    class keyListener extends java.awt.event.KeyAdapter
    //key listener class watches character count
         public void keyTyped(java.awt.event.KeyEvent event){
         Object object = event.getSource();
         for(int i =0; i<7;i++)
              if (object == startHr[i])
                   if ( startHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
                   event.consume(); //if over limit, pretend nothing happened..
              if(object ==startMin[i])
                   if ( startMin[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
                   event.consume();
              if(object==finishHr[i])
                   if ( finishHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
                   event.consume();
              if(object==finishMin[i])
                   if ( finishMin[i].getText().length()>MAX_CHARS && event.getKeyChar(

    Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.So why do you start by writing a 1000 line program. Start with something small. Understand how they work and then incorporate it into your program.
    First. Use the DefaultTableModel. It will do everything you need. Why reinvent the wheel by extending AbstractTableModel. This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418866]posting shows how to create a table and populate it with some data in 5 lines of code or less. It also gives examples of adding new rows of data to the DataModel (something your TableModel can't do) in a couple of lines of code.
    Next, we have Basic Debugging 101. If you have a NullPointerException, then you need to determine which variable is null. I simply added the following code before the line that was causing the problem:
    System.out.println(getValueAt(0, c) + " : " + c);
    return getValueAt(0, c).getClass();
    The value in column 0 was null. So where does the value from the first column come from. Well in your TableModel you tried to create it with one default row of data:
    Object data[][] = { {service, new Integer(5), new Boolean(false)} };
    So it would appear the "service" variable is null.
    Don't post 1000 lines programs again. Create simple code that demonstrates the problem. Chances are while your creating this demo program you will resolve your problem.

  • Creating a copy of an existing JTable that does not have source code.

    Hi
    I am working on a java swing based application. We used a third party API for JTable for showing some data in a table format and also for printing function. As of now print button is printing the whole table being shown in the application. Our new requirement of printing is �Users don�t want to print all the columns being shown in the application and they wanted to have print of columns whatever they would like to see�.
    The above requirement can be fulfilled if I can have a copy of the existing table. Unfortunately we don�t have the source code of the table being shown in the application as we are using 3rd party libraries. Had the source code been there I could have implemented cloneable interface or proto type pattern.
    Can some body help me how can I create a copy of the existing table? Basically the high level approach I thought of is create a new object of the table class and copy the properties/attributes of the existing table to the new table object. But I don�t know what attributes should be copied so that I can have the copy of the original table and how to construct (code) this new table.
    I would be very grateful if some one could help me with this.
    Thanks & Regards
    Srini

    I understood your suggestion. But it would be very difficult to migrate as it requires lot of changes across different tabs of the existing application. This application was developed around 6 years ago. And this change would require lot of regression testing too.
    Do you have any idea of creating the copy of the available JTable object?

  • JTable cell editor not working

    Hello there,
    I am new to Java programming,
    I am trying to create a check box in a table cell which the user should able manipulate when the JTable is showing, the renderer is working fine but the editor is not , the overriden method getTableCellEditorComponent never gets a call, getTableCellRendererComponent does get a call and renderer works fine.
    any ideas whats wrong here ?? or what could be wrong which makes getTableCellEditorComponent not get called ?
    my renderere and editor code is like this
    package com.itrsgroup.swing.componentmanager.dockablemanager;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.util.EventObject;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JCheckBox;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    * A cell renderer and a cell editor for rendering and editing the filters active state.
    public class ActiveCheckBoxRendererEditor extends AbstractCellEditor
    implements TableCellEditor, TableCellRenderer, ItemListener
    private Font font = new Font("Verdana", Font.BOLD, 11 );
    private JCheckBox editor = new JCheckBox("Inactive");
    private JCheckBox renderer = new JCheckBox("Inactive");
    private String strSelectedText;
    private String strNotSelectedText;
    private Color colourActive = new Color(51,153,51);
    private Color colourInActive = Color.RED;
    /** Constructor. */
    public ActiveCheckBoxRendererEditor()
    this( "Selected", "Not Selected" );
    * Constructor.
    * @param strSelText - the text to render when selected.
    * @param strNotSelText - the text to render when not selected.
    public ActiveCheckBoxRendererEditor(String strSelText, String strNotSelText)
    strSelectedText = strSelText;
    strNotSelectedText = strNotSelText;
    renderer = new JCheckBox( strNotSelectedText );
    renderer.setHorizontalTextPosition( SwingConstants.CENTER );
    renderer.setVerticalTextPosition( SwingConstants.TOP);
    renderer.setHorizontalAlignment( SwingConstants.CENTER );
    renderer.setVerticalAlignment( SwingConstants.CENTER );
    renderer.setFont( font );
    editor = new JCheckBox( strNotSelectedText );
    editor.setBackground( UIManager.getColor("Table.selectionBackground") );
    editor.setHorizontalTextPosition( SwingConstants.CENTER );
    editor.setVerticalTextPosition( SwingConstants.TOP );
    editor.setHorizontalAlignment( SwingConstants.CENTER );
    editor.setVerticalAlignment( SwingConstants.CENTER );
    editor.setFont( font );
    editor.addItemListener( this );
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    return editor;
    @Override
    public boolean isCellEditable(EventObject arg0)
    // TODO Auto-generated method stub
    return true;
    @Override
    public Object getCellEditorValue()
    return editor.isSelected();
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    Boolean bool = (Boolean) value;
    renderer.setSelected( bool );
    renderer.setText( bool ? strSelectedText : strNotSelectedText);
    renderer.setForeground( bool ? colourActive : colourInActive );
    if( isSelected )
    renderer.setBackground( table.getSelectionBackground() );
    else
    renderer.setBackground( table.getBackground() );
    return renderer;
    @Override
    public void itemStateChanged(ItemEvent e)
    boolean isSelected = e.getStateChange() == ItemEvent.SELECTED;
    editor.setText( isSelected ? strSelectedText : strNotSelectedText);
    stopCellEditing();
    and this is how I install it on my JTable
    ActiveCheckBoxRendererEditor cbc = new ActiveCheckBoxRendererEditor("Active", "Inactive");
    TableColumn
    activeColumn = this.getColumnModel().getColumn( 3 );
    activeColumn.setCellEditor( cbc);
    activeColumn.setCellRenderer( cbc );
    activeColumn.setPreferredWidth( 80 );
    activeColumn.setMaxWidth( 200 );
    activeColumn.setMinWidth( 80 );thanks
    Ahmed

    Is the column editable?
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Column Hide in JTable

    Hi There,
    We are using Jtable to show data using DefaultTableModel. Now we have to implement some hidden columns in this existing JTable.
    For this we have tried many ways but not succeeded.
    1. We have use width=0 and setting header caption ="" but it shows column with some width insteed of being hidden.
    2. further we tried dtm.setColumnCount(numCols) to set required number of columns to be displayed and it does so but ignore the rest columns. So this way is not useful as well.
    Please suggest us how to implement hidden columns in JTable ?
    Thanx in Adv,

    I would strongly recommend that you use JXTable instead from the SwingX project. It even has a simple Popup Column Control that helps you hide and show columns as desired. But here is some simple code that might be useful
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Enumeration;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class TableUtilities {
         * Restores a hidden TableColumn based on the supplied column index and sets to column
         * width to the supplied preferredWidth
         * @param table
         * @param modelIndex
         * @param columnWidth
        public static void restoreColumn(JTable table, int modelIndex, int columnWidth) {
            if (table.getColumnCount() <= 0) {
                return;
            TableColumn column = new TableColumn(modelIndex);
            column.setHeaderValue(table.getModel().getColumnName(modelIndex));
            column.setCellRenderer(table.getCellRenderer(0, modelIndex));
            column.setCellEditor(table.getCellEditor(0, modelIndex));
            column.setPreferredWidth(columnWidth);
            DefaultTableColumnModel model = (DefaultTableColumnModel) table.getColumnModel();
            model.addColumn(column);
            model.moveColumn(model.getColumnCount() - 1, modelIndex);
         * Restores a hidden TableColumn based on the supplied column index.
         * @param table
         * @param modelIndex
        public static void restoreColumn(JTable table, int modelIndex) {
            TableColumn column = new TableColumn(modelIndex);
            column.setHeaderValue(table.getModel().getColumnName(modelIndex));
            column.setCellRenderer(table.getCellRenderer(0, modelIndex));
            column.setCellEditor(table.getCellEditor(0, modelIndex));
            column.setPreferredWidth(120);
            DefaultTableColumnModel model = (DefaultTableColumnModel) table.getColumnModel();
            model.addColumn(column);
            model.moveColumn(model.getColumnCount() - 1, modelIndex);
         * Restores a hidden TableColumn based on the supplied column name.
         * @param table
         * @param column
        public static void restoreColumn(JTable table, String column) {
            restoreColumn(table, getColumnIndex(table.getModel(), column));
         * Restores a hidden TableColumn based on the supplied column name and sets to column
         * width to the supplied preferredWidth
         * @param table
         * @param columnWidth
         * @param column
        public static void restoreColumn(JTable table, String column, int columnWidth) {
            restoreColumn(table, getColumnIndex(table.getModel(), column), columnWidth);
         * Carries out the process to hide a table column from the view based on the supplied
         * column name
         * @param table
         * @param column
        public static void hideColumn(JTable table, String column) {
            hideColumn(table, table.convertColumnIndexToView(getColumnIndex(table.getModel(), column)));
         * Carries out the process to hide a table column from the view based on the supplied
         * column index
         * @param table
         * @param column
        public static void hideColumn(JTable table, int column) {
            DefaultTableColumnModel model = (DefaultTableColumnModel) table.getColumnModel();
            if (model.getColumnCount() != 0 && column != -1) {
                model.removeColumn(model.getColumn(column));
         * Returns a Vector of Strings containing the columnNames of for the specified TableModel
         * @param model
         * @return
        public static Vector<String> getColumnNames(TableModel model) {
            Vector<String> colNames = new Vector<String>();
            for (int i = 0; i < model.getColumnCount(); i++) {
                colNames.add(model.getColumnName(i));
            return colNames;
         * Returns the first index of the column with the specified name in the supplied TableModel.
         * @param model
         * @param name
         * @return
        public static int getColumnIndex(TableModel model, String name) {
            for (int i = 0; i < model.getColumnCount(); i++) {
                if (model.getColumnName(i).equalsIgnoreCase(name)) {
                    return i;
            return -1;
    }ICE
    Edited by: fadugyamfi on Aug 17, 2009 11:05 AM

  • Multiple selection in JTable

    Hi ,
    The problem is to select multiple rows and columns in the JTable like that of a excel application and have the focus on the first column of the last row. for example if select cells from ( 1,1 ) to ( 4,4), after selection the focus should be in cell (4,1). i have written a prgram( which is below) which uses listSelection to find out the cells which are selected. i found out the cells which are selected also. but i do not know how to get the focus on that cell. i have attached the code below also.. i want to know whether there is any method which set the focus to the particular cell. Can the problem above can be solved in any other way..or a simpler way..
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    class myTable {
    public static void main(String a[] ) {
              JFrame myframe = new JFrame();
              JTable jtable = new JTable(10,10);
              jtable.setCellSelectionEnabled(true);
         // add the listener to the table
    ListSelectionModel listSelectionModel;
         OSSTableSelectionHandler obj = new OSSTableSelectionHandler(jtable,10,10);
         listSelectionModel = jtable.getSelectionModel();
    listSelectionModel.addListSelectionListener(obj);
         myframe.getContentPane().add(jtable);
         myframe.show();
    } // end of public static void main
    } // end of class of myTable
    class OSSTableSelectionHandler implements ListSelectionListener {
                   JTable table;
         int row;
                   int col;
    OSSTableSelectionHandler(JTable tab, int r, int c ) {
         table = tab;
    row = r;
              col = c;
    public void valueChanged(ListSelectionEvent e) {
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                   int i = 0,j = 0;
    int firstIndex = e.getFirstIndex();
    int lastIndex = e.getLastIndex();
    boolean isAdjusting = e.getValueIsAdjusting();
    if (lsm.isSelectionEmpty()) {
    System.out.println(" Selection empty ");
    } else {
    // Find out which indexes are selected.
                        int maxrow = 0 ;
    int minIndex = lsm.getMinSelectionIndex();
    int maxIndex = lsm.getMaxSelectionIndex();
    for ( i = minIndex; i <= maxIndex; i++) {
    if (lsm.isSelectedIndex(i)) {
                                  if ( maxrow < i )
                                       maxrow = i;
                                  for (j = 0;j < col ;j++ )
                                       if ( table.isCellSelected(i,j) )
                                            System.out.println("The selected index is " + i + " " + j);
                             } // end of if                    
    } // end of for
                   // after this maxrow contains the last row that has beeb selected
                   // this for loop is to find out the first column in the maxrow that is selected
                   for (j = 0;j < col ;j ++ )
                        if ( table.isCellSelected(maxrow,j) )
                                  break;
                   // set the focus to the column ( maxrow, j )
    } // end of else
    } // end of fucn value changed
    } // end of class OSSTableSelectionHandler

    Whic cell is focused depends on where you begin your selection. The cell that you press your mouse first will be the focused one. Here is how I implement the mutiple selection functionality in a JTable as what MS Excel provides. This class is independent of my any other package. your table has to have column headers and a upper left JLabel corner(int the scroll pane containing the table) in order to make this class which I named TableSelectionAdapter function properly. You can revise and imporve it as you need, however.
    package petrochina.riped.gui.table.tableadapter;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.datatransfer.*;
    import java.util.*;
    * Enables multiple selection funtionality on <code>JTable</code>s.
    * @author Guanglin Du,SEC of Riped, PetroChina,
    * [email protected]
    * @version 1.0 2002/09/16
    public class TableSelectionAdapter extends MouseAdapter {
    private String newline = "\n";
    private boolean DEBUG = false;
    // private boolean DEBUG = true;
    private JTable myTable = null;
    private boolean shiftKeyDown = false;
    private boolean ctrlKeyDown = false;
    private int firstSelectedColIndex = -1;
    * Constructs with a <code>myTable</code> to simplify its reusability.
    * Guanglin Du, 2002/09/19
    * @param myTable     a <code>JTable</code>
    public TableSelectionAdapter(JTable myTable) {      
    this.myTable = myTable;
    initTableSelection();
    * The initTableSelection method: initializes the row/column/cell
    * selection functionality of the table.
    * Guanglin Du, 2002/09/19
    public void initTableSelection() {      
    getMyTable().setSelectionMode(
              ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
         //Cell selection
         myTable.addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
              myTable.setColumnSelectionAllowed(true);
              myTable.setRowSelectionAllowed(true);
         setMyKeyListener(); //shift/control key listener
         //column selection functionality
         JTableHeader myTableHeader = getMyTable().getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
         //enalbles select-all functionality
         setSelectAllFunction();
    * This setSelectAllFunction isto set the select-all functionality
    * when the upper left corner label of the JTable is clicked.
    * Note: JTable's parent JScrollPane has to be found.
    * Guanglin Du, 2002/09/19
    public void setSelectAllFunction() {      
    Container firstParent = getMyTable().getParent();
    if (firstParent instanceof JViewport) {
         Container secondParent = firstParent.getParent();
         if (secondParent instanceof JScrollPane) {
         JScrollPane myScrollPane = (JScrollPane)secondParent;
         JLabel myLabel =
              (JLabel)myScrollPane.getCorner(JScrollPane.UPPER_LEFT_CORNER );
         myLabel.addMouseListener(this);
    * Detects shift/control key state.
    * DGL, 2002/09/18
    public void setMyKeyListener() {
         getMyTable().addKeyListener(new KeyAdapter(){               
         //keyPressed
         public void keyPressed(KeyEvent e){
              //shift key state
              if(e.isShiftDown())     shiftKeyDown = true;                    
              //control key state
              if(e.isControlDown()) ctrlKeyDown = true;
    //keyReleased
         public void keyReleased(KeyEvent e){
              //shift key state
              if( !e.isShiftDown() ) shiftKeyDown = false;                    
              //control key state
              if( !e.isControlDown() ) ctrlKeyDown = false;
    * Adds the table header listener to enable single/multiple column selection.
    * DGL, 2002/09/17
    public void setTableHeaderListener() {
         JTableHeader myTableHeader = myTable.getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
    * Returns the <code>myTable</code> property value.
    * @return myTable the table that this class handles
    public JTable getMyTable() {
    return myTable;
    * Sets <code>myTable</code> property value of this class.
    * @param myTable the table that this class handles
    public void setJTable(JTable myTable) {
         this.myTable = myTable;
    * Returns the shiftKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getShiftKeyDown(){
         return shiftKeyDown;
    * Return the ctrlKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getCtrlKeyDown(){
         return ctrlKeyDown;
    * This inner class handles the column selection, the same
    * behavior as MS Excel.
    * Guanglin Du, 2002/09/18
    class TableHeaderListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {    
         stopLatestCellEditing(); //To save the data being edited
         if(DEBUG) System.out.print("mousePressed on ");
         JTableHeader myColumnHeader = (JTableHeader)e.getSource();
         Point myPoint = e.getPoint();
         int selectedColIndex = myColumnHeader.columnAtPoint(myPoint);
         if(DEBUG) System.out.print("the header of column "
              + selectedColIndex+newline);
         JTable table = myColumnHeader.getTable();
         //The following column selection methods work only if these
         //properties are set this way
         table.setColumnSelectionAllowed(true);
         table.setRowSelectionAllowed(false);
         int myRowCount = table.getRowCount();
         //makes this table focused, so that setMyKeyListener method can
         //listen for shift/control KeyEvent
         table.requestFocus();
    //     System.out.println("myRowCount = " + myRowCount);
         if( getShiftKeyDown() ){
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(firstSelectedColIndex > -1) {
              table.addColumnSelectionInterval(firstSelectedColIndex, selectedColIndex);
              firstSelectedColIndex = -1;//restore to -1
         } else if( getCtrlKeyDown() ) {
         table.addRowSelectionInterval(0,myRowCount-1);
         table.addColumnSelectionInterval(selectedColIndex,selectedColIndex);
         } else {
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(DEBUG) System.out.println("shiftKeyDown = " + shiftKeyDown
              +";"+" ctrlKeyDown = " + ctrlKeyDown);     
         //saves the first selected column index
         firstSelectedColIndex = selectedColIndex;
    * MouseAdapter implemenation.
    * mousePressed: sets the select-all functionality
    * when upper left corner label of the table is clicked
    * Guanglin Du, 2002/09/18
    public void mousePressed(MouseEvent e) {    
         if(DEBUG) System.out.println("Select all");
         stopLatestCellEditing();//To save the data in editing
         getMyTable().selectAll();
    * Triggers the latest <code>ActionEvent</code> in a table cell to save
    * the latest data. Or, the newly input data will not be stored into the table
    * model and cannot be retrieved.
    public void stopLatestCellEditing() {
    int editingRow = getMyTable().getEditingRow();
    int editingCol = getMyTable().getEditingColumn();
    if (editingRow != -1 && editingCol != -1){
         TableCellEditor cellEditor =
         getMyTable().getCellEditor(editingRow, editingCol);
         cellEditor.stopCellEditing();
    Here is how you can use it in your coding(where myTable is a JTable instance you create):
         /* Adds TableSelectionAdapter to enable all kinds of selection action. */
         TableSelectionAdapter tableSelect = new TableSelectionAdapter(myTable);     

  • How to get data in jtable from database

    i m working on core java application i want to use jtable to show records to user. jtable will get records from mssql database. how to do this.. i m new so plz tell me briefly..with coding...
    thanks

    i have use this link:
    import java.sql.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * This class takes a JDBC ResultSet object and implements the TableModel
    * interface in terms of it so that a Swing JTable component can display the
    * contents of the ResultSet. Note that it requires a scrollable JDBC 2.0
    * ResultSet. Also note that it provides read-only access to the results
    public class ResultSetTableModel implements TableModel {
    ResultSet results; // The ResultSet to interpret
    ResultSetMetaData metadata; // Additional information about the results
    int numcols, numrows; // How many rows and columns in the table
    * This constructor creates a TableModel from a ResultSet. It is package
    * private because it is only intended to be used by
    * ResultSetTableModelFactory, which is what you should use to obtain a
    * ResultSetTableModel
    ResultSetTableModel(ResultSet results) throws SQLException {
         this.results = results; // Save the results
         metadata = results.getMetaData(); // Get metadata on them
         numcols = metadata.getColumnCount(); // How many columns?
         results.last(); // Move to last row
         numrows = results.getRow(); // How many rows?
    * Call this when done with the table model. It closes the ResultSet and
    * the Statement object used to create it.
    public void close() {
         try { results.getStatement().close(); }
         catch(SQLException e) {};
    /** Automatically close when we're garbage collected */
    protected void finalize() { close(); }
    // These two TableModel methods return the size of the table
    public int getColumnCount() { return numcols; }
    public int getRowCount() { return numrows; }
    // This TableModel method returns columns names from the ResultSetMetaData
    public String getColumnName(int column) {
         try {
         return metadata.getColumnLabel(column+1);
         } catch (SQLException e) { return e.toString(); }
    // This TableModel method specifies the data type for each column.
    // We could map SQL types to Java types, but for this example, we'll just
    // convert all the returned data to strings.
    public Class getColumnClass(int column) { return String.class; }
    * This is the key method of TableModel: it returns the value at each cell
    * of the table. We use strings in this case. If anything goes wrong, we
    * return the exception as a string, so it will be displayed in the table.
    * Note that SQL row and column numbers start at 1, but TableModel column
    * numbers start at 0.
    public Object getValueAt(int row, int column) {
         try {
         results.absolute(row+1); // Go to the specified row
         Object o = results.getObject(column+1); // Get value of the column
         if (o == null) return null;
         else return o.toString(); // Convert it to a string
         } catch (SQLException e) { return e.toString(); }
    // Our table isn't editable
    public boolean isCellEditable(int row, int column) { return false; }
    // Since its not editable, we don't need to implement these methods
    public void setValueAt(Object value, int row, int column) {}
    public void addTableModelListener(TableModelListener l) {}
    public void removeTableModelListener(TableModelListener l) {}
    the table is showing column name from database but not showing the data in row now what to do

  • Problem in cell selection in JTable Java Swing

    hii
    I am using JTable that shows data from database. I have developed one functionality. I change one cell value and then select multiple cell. If I press F12 function key then it copies first selected value and past it to another selected cells. it is working properly but when I press F12 it sets the last selected cell in editable mode. I want that all cell which has been pasted should be selected (with default blue colour not in editing mode). I am using ListSelectionListener for JTable Cell Selection and KeyListener for F12 functionality.
    Please give some solution
    I can not override editCellAt Method because i have already extended JFrame. and i tried to do this with Jtable.getSelectedColumn and getSelectedRow it is displaying the same value, by this how can I get the particular area of selection means Row nd Column Selected.
    How would I know the current selection when user selects more than one cell???
    Thanks
    Edited by: 850979 on 11-Apr-2011 02:13
    Edited by: 850979 on 11-Apr-2011 03:59

    camickr wrote:
    Presumably, JTable installs an action for the F12 key that results in starting editing the last selected cell.
    There are no bindings for F12. See the [url http://www.camick.com/java/blog.html?name=key-bindings]Key Bindings listing. (...)
    Right.
    Of course it doesn't make sense that a F? key should invoke the editorI thought he meant F2 ("edit" on Windows), so that sounded natural.
    All KeyEvents are passed to the editor for the cell and the editor is psuedo invoked. That is, the caret is not placed on the text field used as the editor, but the character typed is added to the editor. You can then either use tab/enter to save the text or use the escape key to cancel the editing.Thanks for the explanation. I had never noticed (I kept on double-clicking my JTable cells when I wanted to edit them! :o)
    Of course it doesn't make sense that a F? key should invoke the editor, but this is a by product of all KeyEvents being forwarded so you don't have to have special Key Bindings for every character.You're right - as always.
    They (Sun) could have filtered out some of the keys such as those, though, because as noted by the OP the current behavior is unintuitive.
    To better control when the cell is editable based on the KeyEvent you can override the table with code like <snipped>
    As you suggested using a Key Binding will prevent this behaviour as well (but only for that key).Right again, but in this specific case that is acceptable (the developer wants to attach a specific behavior to a specific key only).
    OP here is an SSCCE of that second approach:
    public class TestKeyBindingsOnJTable {
        public static void main(String... args) {
            final DefaultTableModel dtm = new DefaultTableModel(new String[] {"A", "B"}, 0);
            dtm.addRow(new String[]{"A1", "B1"});
            dtm.addRow(new String[]{"A2", "B2"});
            dtm.addRow(new String[]{"A3", "B3"});
            JTable table = new JTable(dtm);
            table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "clear");
            table.getActionMap().put("clear", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    dtm.removeRow(0);
            JOptionPane.showMessageDialog(null, table);
    }Edited by: jduprez on Apr 8, 2011 9:36 PM

Maybe you are looking for