Store a reference to a row from JTable

Hello everyone!
Me and my school mates are working on a project for a peer to peer application for the school. For file sending we wrote a class that extends Thread. We have a JTable to represent the downloading files. If the mentioned class for sending a file is created, I want to store into it's instance a reference to a row from the JTable. So I can always edit the cell in the tables row that represents the progress of downloading. Until now we were accessing the proper tables row over the rows index. But if we delete some rows from the table (we wand to remove finished downloads), the indexes get mixed up.
I know that .NET has a class that represents a single row in the table. I would like to store the instance of a row in my class that downloads the file in my Java project.
Thanks for further help!
Regards.

I know that .NET has a class that represents a single row in the table.
I would like to store the instance of a row in my class that downloads the file in my Java project.You need to create a custom TableModel that stores an Object containing the row information.
Here is a basic shell to get you started:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610618
You will need to add method to add/remove rows from the model. You will then need to search the TableModel to find the Object in order to determined which row to update.

Similar Messages

  • How to remove a row from JTable

    Hi!
    I'm used to remove rows from JTables getting the model and doing a removeRow(num) like this:
    ((DefaultTableModel)jTable1.getModel()).removeRow(0);
    But with ADF and JDeveloper the model says it's a JUTableBinding.JUTableModel but its not accessible.
    How to remove a row in Jdeveloper 10.1.3.4.0?

    Or maybe is just better to refresh data in the jTable but I do not know either like doing it.

  • Deleting a row from JTable

    I am trying to delete a row from a JTable whenever the button on the last column is pressed. I know to do this, I can use the removeRow(int) method of the tableModel. But the odd thing is when I try to get a handle to the TableModel from the JTable to use that function, i.e. table.getModel().removeRow(int) it doesn't work. But if I explicitly pass in the tableModel into my class it does work. Here's the code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.UIManager;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableCellEditor;
    import javax.swing.AbstractCellEditor;
    import javax.swing.table.DefaultTableModel;
    public class tester4 extends JFrame
         protected final int BUTTON_COL = 2;
         private TableCellRenderer defaultRenderer;
         private TableCellEditor defaultEditor;
         private JTable workingTable;
         private String[] transactionCols = {"Qty", "Product", "Cancel"};
         private Object[][] data = {{5, "prod1", "Cancel"},
                   {6, "prod2", "Cancel"},
                   {7, "prod3", "Cancel"}};
        public tester4()
              workingTable = new JTable(tableModel);
              workingTable.setName("Working Table");
              defaultRenderer = workingTable.getDefaultRenderer(JButton.class);
              defaultEditor = workingTable.getDefaultEditor(Object.class);
              StatusTableRenderer testRenderer = new StatusTableRenderer(defaultRenderer, defaultEditor, workingTable, tableModel);
              workingTable.setDefaultRenderer(Object.class, testRenderer);
              workingTable.setDefaultEditor(Object.class, testRenderer);
            JScrollPane scrollPane = new JScrollPane( workingTable );
            getContentPane().add( scrollPane );
         private DefaultTableModel tableModel = new DefaultTableModel(data, transactionCols){
              // Only allow button column to be editable, if there is an actual
              // button in that row          
              public boolean isCellEditable(int row, int col){
                   return (col == BUTTON_COL && data[row][col] != "") ? true : false;
              // Overriden getColumnClass method that will return the object
              // class type of the first instance of the data type otherwise
              // returns the Object.class
              public Class getColumnClass(int column){
                for (int row = 0; row < getRowCount(); row++){
                    Object o = getValueAt(row, column);
                    if (o != null){ return o.getClass(); }
                return Object.class;
        public static void main(String[] args)
            tester4 frame = new tester4();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        public class StatusTableRenderer extends AbstractCellEditor
                                                implements TableCellRenderer,
                                                               TableCellEditor,
                                                               ActionListener{
             private TableCellRenderer defaultRenderer;
             private TableCellEditor defaultEditor;
             private JButton cancelButton;
             private JButton editButton;
             private String text;
             private int buttonColumn;
             private int selectedRow;
             private JTable table;
             private DefaultTableModel tableModel;
             public StatusTableRenderer(TableCellRenderer renderer,
                                           TableCellEditor editor,
                                           JTable table,
                                           DefaultTableModel tableModel){
                  defaultRenderer = renderer;
                  defaultEditor = editor;
                  this.table = table;
                  this.tableModel = tableModel;
                  buttonColumn = table.getColumnCount() - 1;
                cancelButton = new JButton();
                editButton = new JButton();
                editButton.setFocusPainted(true);
                editButton.addActionListener(this);
             public StatusTableRenderer(TableCellRenderer renderer,
                                                TableCellEditor editor,
                                                JTable table,
                                                DefaultTableModel tableModel,
                                                int _buttonColumn){
                  this(renderer, editor, table, tableModel);
                  buttonColumn = _buttonColumn;
             public Component getTableCellRendererComponent(JTable table, Object value,
                       boolean isSelected, boolean hasFocus, int row, int column) {
                  if (column == buttonColumn){
                       if (hasFocus){
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       else if (isSelected){
                            cancelButton.setForeground(table.getSelectionForeground());
                            cancelButton.setBackground(table.getSelectionBackground());
                       else{
                            cancelButton.setForeground(table.getForeground());
                            cancelButton.setBackground(UIManager.getColor("Button.background"));
                       cancelButton.setText( (value == null) ? "" : value.toString() );
                       return cancelButton;
                return defaultRenderer.getTableCellRendererComponent(
                            table, value, isSelected, hasFocus, row, column);
             public Component getTableCellEditorComponent(JTable table, Object value,
                       boolean isSelected, int row, int column){
                  if (column == buttonColumn){
                       text = ((value == null) ? "": value.toString());
                       editButton.setText(text);
                       selectedRow = row;
                       return editButton;
                  return defaultEditor.getTableCellEditorComponent(
                            table, value, isSelected, row, column);
            public Object getCellEditorValue()
                return text;
            public void actionPerformed(ActionEvent e)
                fireEditingStopped();
                // This works
                tableModel.removeRow(selectedRow);
               // This does not work
              //  table.getModel().removeRow(selectedRow);
    }Take a look at the actionPerfformed method. One way of doing it works, one doesn't. Just trying to understand why me getting a handle to the tableModel through the table doesn't work.
    Message was edited by:
    deadseasquirrels

    It gives me a run-time error Well then your question should be "why do I get this run-time error" and then you would quote the error. Be more descriptive. "It doesn't work" is not descriptive.
    table.getModel().removeRow(selectedRow);I don't use JDK1.5 either. But if you are saying that the above line compiles cleanly with JDK1.5 (because of the auto-boxing feature, or whatever its called), then I see no reason why the code wouldn't work since it recognizes the class as a DefaultTableModel.
    Presumably you commented out the other line so you don't try to delete the row twice. Otherwise you might be getting a indexing error.

  • Problem removing rows from JTable

    Hello,
    I'm having an issue with a JTable that I'm using. At one point in my application, I want to remove all the rows from the table and regenerate them (from a database). When I try to remove the rows and do nothing else, they remain in the table. The rows are being removed from the model, as I have verified this in code, but the display does not refresh at all.
    I am using custom renderers to change the background color of a cell based on its value, and I disabled them to see if that was the problem, but alas, it is not.
    Any suggestions or ideas why this may be occurring?

    I am using model.setRowCount(0); to clear the model, however the display never refreshes. Then you are doing something wrong because its that simple. Only a single line of code is required.
    Perhaps I should have included this in my original post.Actually, you should have included demo code in your original post. That way we don't have to guess what you are doing.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • White patch after removing row from JTable

    I am working with JTable and removing item from table on clicking on button but after removing row there is white Patch on that row. I don�t want to show this white patch.
    I did repaint table but that is also not working.
    Any thoughts !!!!!!!

    javax.swing.SwingUtilities.invokeLater(new Runnable(){
                public void run(){
                  museTable.setBackground(Color.black);//your color here
              });

  • Delete rows from JTable

    Hello
    I use a JTable with a custom table model that extends javax.swing.table.DefaultTableModel.
    I haven't overwrote the method
    public void removeRow(int row)Now when i use this method the rows always get removed from the end. It doesn't matter which value the parameter row has.
    Even when i call
    myTableModel.removeRow( 0 );it removes the rows at the end of the table.
    It would be nice if someone could help me with this.
    Regards, Michelle

    It's not so easy to do this because it's a big project, but here is the code of the table model.
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.util.*;
    public class AssignmentsTableModel2 extends DefaultTableModel implements TableModelListener
         static final long serialVersionUID = 41L;
         public AssignmentsTableModel2(String[][] arg1, String[] arg2)
              super(arg1, arg2);
         public Vector getColumnIdentifiers()
              return columnIdentifiers;
         @Override
         public int getColumnCount()
              return this.columnIdentifiers.size();
         @Override
         public int getRowCount()
              return this.dataVector.size();
         @Override
         public String getColumnName(int col)
            return (String)this.columnIdentifiers.elementAt( col );
         @Override
         public Object getValueAt(int rowIndex, int columnIndex)
              return ((Vector)this.dataVector.elementAt( rowIndex )).elementAt( columnIndex );
         @Override
         public void setValueAt( Object val, int rowIndex, int columnIndex )
              ((Vector)this.dataVector.elementAt( rowIndex )).set( columnIndex, val);
              fireTableCellUpdated( rowIndex, columnIndex );
         @Override
         public void tableChanged(TableModelEvent e)
         @Override
         public void setColumnIdentifiers(Vector columnIdentifiers)
              super.setColumnIdentifiers(columnIdentifiers);
         @Override
         public void removeRow(int row)
              this.dataVector.remove(row);
              System.out.println(row + " to remove");
              this.fireTableStructureChanged();
              //super.removeRow(row);
    }I need the model to change the background color of the cells at runtime and I now overwrote the removeRow() method, but it's still the same problem.
    Also I have a custom JTable class that colours the TableHeader of the selected column.
    class PaintedTable extends JTable {
        private static final long serialVersionUID = 1L;
        PaintedTable(AssignmentsTableModel2 atm)
            super(atm);
            setOpaque(false);
            ((JComponent) getDefaultRenderer(Object.class)).setOpaque(false);
        @Override
        public void paintComponent(Graphics g)
             //System.out.println("paint table");
            Color background = new Color(168, 210, 241);
            Color controlColor = new Color(230, 240, 230);
            int width = getWidth();
            int height = getHeight();
            Graphics2D g2 = (Graphics2D) g;
            Paint oldPaint = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
            g2.fillRect(0, 0, width, height);
            g2.setPaint(oldPaint);
            for (int row : getSelectedRows())
                Rectangle start = getCellRect(row, 0, true);
                Rectangle end = getCellRect(row, getColumnCount() - 1, true);
                g2.setPaint(new GradientPaint(start.x, 0, Color.orange, (int) ((end.x + end.width - start.x) * 1.25), 0, controlColor));
                g2.fillRect(start.x, start.y, end.x + end.width - start.x, start.height);
                //System.out.println("rect: (" + start.x + ", " + start.y + ") + (" + (end.x + end.width - start.x) + ", " + start.height +")");
            super.paintComponent(g);
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;  
    AssignmentsTableModel2 atm = new AssignmentsTableModel2(this.columnValues, this.columnHeaders);     
    PaintedTable table = new PaintedTable( this.atm );

  • HOW TO EXECUTE A STORE PROCEDURE THAT RETURN MULTIPLE ROWS FROM A QUERY

    I NEED TO CREATE AND USE A STORE PROCEDURE THAT IS GOING TO DO A SELECT STATEMENT AN THE RESULT OF THE SELECT STATEMENT IS RETURN IN SOME WAY TO THE REQUESTER.
    THIS CALL IS MADE BY AN EXTERNAL LANGUAGE, NOT PL/SQL OR FORMS APPLICATION. USING FOR EXAMPLE ODBC AND VISUAL BASIC. WHAT I NEED TO DO IS ADD A DATA ACCESS LAYER TO MY APPLICATION AND I ALREADY HAVE IT DONE FOR MS SQL SERVER, BUT I NEED THE SAME FUNCTIONALITY ACCESSING AN ORACLE DATABASE.
    FLOW:
    1. VB CREATE A ODBC CONNECTION TO A ORACLE DATABASE
    2. VB EXECUTE A STORE PROCEDURE
    3. THE STORE PROCEDURE RETURNS TO THE VB APPLICATION THE RESULT OF THE QUERY THAT IS INSIDE OF THE STORE PROCEDURE.(I.E. THE STORE PROCEDURE IS A BASIC SELECT, NOTHING COMPLEX)
    4. VB DISPLAY THE RESULT IN A GRID
    FOR SURE I CAN DO THE SELECT DIRECTLY TO ORACLE, BUT FOR PERFORMANCE REASONS AND SCALABILITY, I'LL LIKE IT TO DO IT USING A STORE PROCUDURES
    IS THIS POSIBLE?, HOW?
    THANKS

    Certainly, it's possible. First, define a stored procedure that includes an OUT parameter which is a REF CURSOR. Then, call the stored procedure via ODBC omitting the OUT parameter from the list of parameters. IT will automatically be returned as a result set. Syntax for both is below...
    CREATE PROCEDURE foo (inParam in varchar2, resultSet OUT REF CURSOR )
    In ODBC:
    {call foo( 'someData' )}
    Justin

  • How do I get filtered rows from JTable

    Hello,
    I'm using RowSorter to filter my data on a JTable, but now I need to get the rows that were not filtered out so I can export it to a CSV file.
    Any ideas how to accomplish this?
    Thanks,
    Thiago

    According to the javadoc (http://java.sun.com/javase/6/docs/api/javax/swing/table/TableRowSorter.html)
    If you have enabled filtering convertRowIndexToView will return -1 for locations that are not visible in the view.Hopefully you can deduce the rest.

  • How to Remove Checked Rows from JTable

    Hello All,
    I am currently working on a JTable, in which I have also include a JCheckbox. What i have to do is to remove all the Rows which are Checked in the JTable, when the 'Delete' button is clicked.
    Please tell me how i can this can be done, it will be of great help.
    Thanks,
    Shikha

    Loop through the TableModel, Use the getValueAt(...) method to find rows with a selected checkBox. Then use the removeRow(...) method of the DefaultTableModel to remove the row.
    Note: make sure your loop starts at the last row of the table and counts down to 0, to simplify the delete logic.

  • Remove row from JTable

    I have a JTable, and after selecting a row of the JTable a dialog opens for me to perform an action. But when I close the dialog I want that the row I have selected has disapeared, that means that I want to refresh the view removing the selected row. How can I do this?

    DefaultTableModel.removeRow(...);

  • Deleting a row from a JTable using a custom TableModel

    Before I waste any of your time I would like to go ahead and just say that I have searched through the forum using "delete row from Jtable" as the search keywords and while I have found very closely related issues, they have not solved my problem. I have found code postings by carmickr and his arguments as to why we should use DefaultTableModel instead of having created our own custom TableModel, and while I do agree, I just am not quite confident enough in applying it to my scenario. See I am reading from a file a bunch of Contractor objects and I am stuffing it into an arraylist which I am using in the following code posting to populate my TableModel which the JTable object in the gui then uses.
    My problem is that everything works except when I delete and when I delete I understand that the index is changing because I just removed a row from the arraylist object. Suppose I have 33 rows displaying in the GUI. Now after I delete say row #23, the delete function works and dutifuly the row disappears from the table, but if I try to delete a row say...the last row, it does not work and throws me an IndexOutOfBoundsException which totally makes sense. My question is how do I go about fixing it? Do I have to do something with the setRowCount method?
    Any help is appreciated.
    Cheers,
    Surya
    * ContractorTableModel.java
    * Created on January 12, 2006, 11:59 PM
    package code.suncertify.gui;
    import java.util.ArrayList;
    import java.util.logging.Logger;
    import javax.swing.table.AbstractTableModel;
    import code.suncertify.db.Contractor;
    * @author Surya De
    * @version 1.0
    public class ContractorTableModel extends AbstractTableModel {
         * The Logger instance. All log messages from this class are routed through
         * this member. The Logger namespace is <code>sampleproject.gui</code>.
        private Logger log = Logger.getLogger("code.gui");
         * An array of <code>String</code> objects representing the table headers.
        private String [] headerNames = {"Record Number", "Contractor Name",
        "Location", "Specialties","Size", "Rate",
        "Owner"};
         * Holds all Contractor instances displayed in the main table.
        private ArrayList <Object> contractorRecords = new ArrayList<Object>(5);
         * Returns the column count of the table.
         * @return An integer indicating the number or columns in the table.
        public int getColumnCount() {
            return this.headerNames.length;
         * Returns the number of rows in the table.
         * @return An integer indicating the number of rows in the table.
        public int getRowCount() {
            return this.contractorRecords.size();
         * Gets a value from a specified index in the table.
         * @param row An integer representing the row index.
         * @param column An integer representing the column index.
         * @return The object located at the specified row and column.
        public Object getValueAt(int row, int column) {
            Object [] temp = (Object[]) this.contractorRecords.get(row);
            return temp[column];
         * Sets the cell value at a specified index.
         * @param obj The object that is placed in the table cell.
         * @param row The row index.
         * @param column The column index.
        public void setValueAt(Object obj, int row, int column) {
            Object [] temp = (Object []) this.contractorRecords.get(row);
            temp [column] = obj;
         * Returns the name of a column at a given column index.
         * @param column The specified column index.
         * @return A String containing the column name.
        public String getColumnName(int column) {
            return headerNames[column];
         * Given a row and column index, indicates if a table cell can be edited.
         * @param row Specified row index.
         * @param column Specified column index.
         * @return A boolean indicating if a cell is editable.
        public boolean isCellEditable(int row, int column) {
            return false;
         * Adds a row of Contractor data to the table.
         * @param specialty
         * @param recNo The record number of the row in question.
         * @param name The name of the contractor.
         * @param location Where the contractor is located
         * @param size Number of workers for the contractor
         * @param rate The contractor specific charge rate
         * @param owner Name of owner
        public void addContractorRecord(int recNo, String name,
                String location, String specialty,
                int size, float rate, String owner) {
            Object [] temp = {new Integer(recNo), name,
            location, specialty, new Integer(size),
            new Float(rate), owner};
            this.contractorRecords.add(temp);
            fireTableDataChanged();
         * Adds a Contractor object to the table.
         * @param contractor The Contractor object to add to the table.
        public void addContractorRecord(Contractor contractor) {
            Object [] temp = {new Integer(contractor.getRecordNumber()),
            contractor.getName(), contractor.getLocation(),
            contractor.getSpecialties(), new Integer(contractor.getSize()),
            new Float(contractor.getRate()), contractor.getCustomerID()};
            this.contractorRecords.add(temp);
            fireTableDataChanged();
         * Deletes a row of Contractor data to the table.
         * @FIXME Now that I deleted a row then I will have to reset the internal structure so that I can delete again
         * @param recNo The record number of the row in question.
        public void deleteContractorRecord(int recNo) {
            contractorRecords.remove(recNo - 1);
            fireTableRowsDeleted(recNo -1, recNo - 1);
    }

    Wow that was a very quick response. Thanks camickr. I am only trying to delete a single row. I do not know how to go about posting a test program for the code I have posted above because honestly the gui itself is 800 lines of code, and then the file reading class is quite funky in itself. I can maybe email you the entire Netbeans project including code so if you are using Netbeans 5 RC2 you can run the code and see for yourself, but that would not be considerate of me.
    See I am trying to delete any row at any time...but only one at a time not multiple rows...so if a user decides to delete row 23 and then tries to delete the last row which happens to be row 33 in my case, my setup should be smart enough to still allow to delete the row.

  • How to remove a row from a jtable with DefaultTableModel

    Hi to all,]
    I want to remove a row from jtable. I am using DefaultTableModel.
    I have got some example but every example is given with AbstractTableModel
    Please help me...
    Thanks and Regards

    I want to remove a row from jtable. I am using DefaultTableModel.How do you program without reading the API.
    The name of the method you use is "removeRow". How hard is that to find by reading the API?
    Not only do you not bother to read the API, you don't even bother to read and respond to your old postings when you get help:
    http://forum.java.sun.com/thread.jspa?threadID=5137773
    http://forum.java.sun.com/thread.jspa?threadID=5134667
    http://forum.java.sun.com/thread.jspa?threadID=5131162
    Your on your own in the future.

  • Problem in adding/deleting rows in JTable

    I am trying to add /remove rows from JTable whose first column is JButton and others are JComboBox's.If no rows are selected,new row is added at the end.If user selects some row & then presses insert button,new row is added below it.Rows can only be deleted if user has made some selection.Kindly help me,where i am making mistake.If any function is to be used.My code is as follows....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class JButtonTableExample extends JFrame implements ActionListener{
    JComboBox mComboLHSType = new JComboBox();
    JComboBox mComboRHSType = new JComboBox();
    JLabel mLabelLHSType = new JLabel("LHS Type");
    JLabel mLabelRHSType = new JLabel("RHS Type");
    JButton mButtonDelete = new JButton("Delete");
    JButton mButtonInsert = new JButton("Insert");
    JPanel mPanelButton = new JPanel();
    JPanel mPanelScroll = new JPanel();
    JPanel mPanelCombo = new JPanel();
    DefaultTableModel dm ;
    JTable table;
    int currentRow = -1;
    static int mSelectedRow = -1;
    public JButtonTableExample()
    super( "JButtonTable Example" );
    makeForm();
    setSize( 410, 222 );
    setVisible(true);
    private void makeForm()
    this.getContentPane().setLayout(null);
    mPanelCombo.setLayout(null);
    mPanelCombo.setBorder(new LineBorder(Color.red));
    mPanelCombo.setBounds(new Rectangle(1,1,400,30));
    mLabelLHSType.setBounds(new Rectangle(26,5,71,22));
    mComboLHSType.setBounds(new Rectangle(83,5,100,22));
    mLabelRHSType.setBounds(new Rectangle(232,5,71,22));
    mComboRHSType.setBounds(new Rectangle(292,5,100,22));
    mPanelCombo.add(mLabelLHSType,null);
    mPanelCombo.add(mComboLHSType,null);
    mPanelCombo.add(mLabelRHSType,null);
    mPanelCombo.add(mComboRHSType,null);
    mPanelScroll.setLayout(null);
    mPanelScroll.setBorder(new LineBorder(Color.blue));
    mPanelScroll.setBounds(new Rectangle(1,28,400,135));
    mPanelButton.setLayout(null);
    mPanelButton.setBorder(new LineBorder(Color.green));
    mPanelButton.setBounds(new Rectangle(1,165,400,30));
    mButtonInsert.setBounds(new Rectangle(120,5,71,22));
    mButtonDelete.setBounds(new Rectangle(202,5,71,22));
    mButtonDelete.addActionListener(this);
    mButtonInsert.addActionListener(this);
    mPanelButton.add(mButtonDelete,null);
    mPanelButton.add(mButtonInsert,null);
    dm = new DefaultTableModel();
    //dm.setDataVector(null,
    //new Object[]{"Button","Join","LHS","Operator","RHS"});
    dm.setDataVector(new Object[][]{{"","","","",""}},
    new Object[]{"","Join","LHS","Operator","RHS"});
    table = new JTable(dm);
    table.getTableHeader().setReorderingAllowed(false);
    table.setRowHeight(25);
    int columnWidth[] = {20,45,95,95,95};
    TableColumnModel modelCol = table.getColumnModel();
    for (int i=0;i<5;i++)
    modelCol.getColumn(i).setPreferredWidth(columnWidth);
    //modelCol.getColumn(0).setCellRenderer(new ButtonRenderer());
    //modelCol.getColumn(0).setCellEditor(new ButtonEditor(new JCheckBox()));
    modelCol.getColumn(0).setCellRenderer(new ButtonCR());
    modelCol.getColumn(0).setCellEditor(new ButtonCE(new JCheckBox()));
    modelCol.getColumn(0).setResizable(false);
    setUpJoinColumn(modelCol.getColumn(1));
    setUpLHSColumn(modelCol.getColumn(2));
    setUpOperColumn(modelCol.getColumn(3));
    setUpRHSColumn(modelCol.getColumn(4));
    JScrollPane scroll = new JScrollPane(table);
    scroll.setBounds(new Rectangle(1,1,400,133));
    mPanelScroll.add(scroll,null);
    this.getContentPane().add(mPanelCombo,null);
    this.getContentPane().add(mPanelScroll,null);
    this.getContentPane().add(mPanelButton,null);
    }//end of makeForm()
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource() == mButtonInsert)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before Insert CURRENT ROW"+currentRow);
    if(currentRow == -1)
    int rowCount = dm.getRowCount();
    //mSelectedRow = rowCount-1;
    //table.clearSelection();
    dm.insertRow(rowCount,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    else
    table.clearSelection();
    dm.insertRow(currentRow+1,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("After INSERT CURRENT ROW"+currentRow);
    if(ae.getSource() == mButtonDelete)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before DELETE CURRENT ROW"+currentRow);
    if(currentRow != -1)
    dm.removeRow(currentRow);
    table.clearSelection();
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("Selected Row"+mSelectedRow);
    else
    JOptionPane.showMessageDialog(null, "Select row first", "alert", JOptionPane.ERROR_MESSAGE);
    //System.out.println("DELETE CURRENT ROW"+currentRow);
    public void setUpJoinColumn(TableColumn joinColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("AND");
    comboBox.addItem("OR");
    comboBox.addItem("NOT");
    joinColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    joinColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = joinColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpLHSColumn(TableColumn LHSColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Participant1");
    comboBox.addItem("Participant2");
    comboBox.addItem("Variable1");
    LHSColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    LHSColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = LHSColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpOperColumn(TableColumn operColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("=");
    comboBox.addItem("!=");
    comboBox.addItem("Contains");
    operColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    operColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = operColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpRHSColumn(TableColumn rhsColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Variable1");
    comboBox.addItem("Constant1");
    comboBox.addItem("Constant2");
    rhsColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    rhsColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = rhsColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public static void main(String[] args) {
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Button as a renderer for the table cells
    class ButtonCR implements TableCellRenderer
    JButton btnSelect;
    public ButtonCR()
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    if (column != 0) return null; //meany !!!
    //System.out.println("Inside renderer########################Selected row");
    //btnSelect.setText(value.toString());
    //btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    return btnSelect;
    }//end fo ButtonCR
    //Default Editor for table
    class ButtonCE extends DefaultCellEditor implements ActionListener
    JButton btnSelect;
    JTable table;
    //Object val;
    static int selectedRow = -1;
    public ButtonCE(JCheckBox whoCares)
    super(whoCares);
    //this.row = row;
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    btnSelect.addActionListener(this);
    setClickCountToStart(1);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column)
    if (column != 0) return null; //meany !!!
    this.selectedRow = row;
    this.table = table;
    table.clearSelection();
    System.out.println("Inside getTableCellEditorComponent");
    return btnSelect;
    //public Object getCellEditorValue()
    //return val;
    public void actionPerformed(ActionEvent e)
    // Your Code Here...
    System.out.println("Inside actionPerformed");
    System.out.println("Action performed Row selected "+selectedRow);
    btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    }//end of ButtonCE

    Hi,
    All the thing you have to do is to return a boolean for the column. JTable will use a checkbox (as default) to show boolean values.

  • JTable: How to reference the selected row during a drag?

    I am implementing Drag and Drop on the rows of a JTable.
    I want to change the background colour of each successive JTable row ("highlight" the row) as another row is dragged over it (I already have similar functionality implemented in a custom TableCellRenderer, but the Drag and Drop code knocks it out) .
    I have run into a problem: All of the JTable methods refer to the rows as ints--0, 1, 2, etc.
    Here is my approach:
    I get the reference to the row by using:
         "int dragEnteredRow = table.rowAtPoint( e.getPoint() ); "
    With the intention to use the variable dragEnteredRow to change each row's foreground colour:
         "dragEnteredRow.setForeground( selected ); "
    That gives me an error message from the compiler:
    "... Can't invoke a method on a int.
         dragEnteredRow.setBackground( Color.yellow ); ... "
    Here is some more of the code (it implements the Macintosh Drag and Drop API):
    [javacode]     
    "     public boolean dragMoved( DragEvent e ) {
         dragEntered( e );
              return true;
         public boolean dragEntered( DragEvent e ) {
         int dragEnteredRow = table.rowAtPoint( e.getPoint() );
              dragEnteredRow.setBackground( Color.yellow ); // These two lines fail at the compiler
    //     table.rowAtPoint( e.getPoint() ).setBackground( Color.yellow );
              if ( dragEnteredRow == -1 ) {;
                   System.out.println( "out of bounds !!" );
              } else {               
                   System.out.println( "Drag Entered at : Row" + dragEnteredRow ); // This test code works
                   System.out.println( "" );
                   return true;
    [javacode]
    My Question: What is the proper approach to solving this problem?
    Many thanks in advance for a solution.
         

    the method rowAtPoint(e.getPoint()) returns an integer with the index of the row at point e, and not the instance of the row.
    You have to use this integer to reference the row through a method like getValueAt(row int,col int) of the DefaultTableModel
    Hope this helps

  • Keeping Viewport position when rows above viewport are deleted from JTable?

    I have a JTable backed by a vector. I have, say, 30 rows and my Viewport is showing the ten rows from row 11 to 20. I want to be able to delete one of the first 10 rows without having my viewport slide so that it displays what were formerly rows 12-21. Essentially, I want the position of the viewport anchored to the rows shown in the viewport, not anchored to the row numbers position in the table. I have been able to do this by moving the viewport Rectangle by getRowHeight with each delete but that makes my table flicker when rows are deleted and is generally an ugly solution. The table is sorted so that the rows are not necessarily displayed in the order in which they reside in the vector.
    Here is the ugly way to accomplish what I'm talking about:
    JViewport viewport = null;
    java.awt.Point p = null;
    // if the order is being removed from above the current viewport
    // scroll down one row so the viewport remains stationary during deletes.
    if (table != null && (table.getParent() instanceof JViewport)) {
         viewport = (JViewport) table.getParent();
         int h = table.getRowHeight();
         Rectangle rect = table.getCellRect(row, 0, true);
         p = viewport.getViewPosition();
         //if the row being deleted is above the viewport
         if (rect.getY() + h < p.getY()) {
              // The location of the view relative to the table
              // Scroll the area into view.
              h = h * -1;
              p.translate(0, h);
              viewport.setViewPosition(p);
    displayedVector.remove(row);
    fireTableRowsDeleted(row, row);
    Thanks!
    Andrew Munn
    [email protected]

    What am I doing wrong?Nothing.
    The DataModel stores data. The ColumnModel is used by the table to display the data from the DataModel in a certain order. If you don't want to display a column that fine, but there is no need to delete the data.
    If you want to delete data from the DataModel the look at the DefaultTableModel API setColumnCount(int) method.

Maybe you are looking for

  • Fpga DMA FIFO compilation error

    Hello, I have a cRIO 9074 with FPGA. I am trying a simple piece of code to learn how to aquire data that is generated on the FPGA at a rate of 10 KHz and transfer it to the Host VI for processing it later offline. However, I encounter this compilatio

  • Execution sequence of connect by and group by

    Hi All, I know 'connect by' precedes 'where clause'. And I can use a test case to test this. But I can't figure out which comes first, connect by and group by. Can someone give me some tips on this, pleaes? And another confusion of mine is execution

  • S_ALR_87012357 requires plant

    To SAP Experts How can I add plant to S_ALR_87012357 VAT Report?  Or is there another VAT report that has plant as output field?

  • Moving Raid0 stripe from sata 1&2 to 3&4

    Like topic says, I wanna move my raid0 stripe from sata1&2 to 3&4, I'm pretty new to raid setups so I tought I'd ask first if it's possible without losing data & still beyin able to boot from that array. Also some info on how it should be done would

  • Update to OSX Mountain Lion ?

    Hi all, I have a MacBook Pro which I bought circa June 2007, currently have software 10.6.8 with 2.2 GHz processor and 2GB RAM. Will this be enough to update to ML and has anyone else had any problems with an old machine? I have about 15GB of Hard dr