Clicking JButton in JTable

Hello all,
I have populated a JTable with Buttons and need for them to appear to be clicked (become depressed) when they are clicked.
Currently, I have found some way to handle click events on them, but the display is not updated to show that they are clicked.
How can this be done??
fyi, the click code adds a mouse listener to the table, which determines which cell is clicked based on location and forwards the event to appropriate handler. it goes something like this:
private void forwardEventToHandlers(MouseEvent e) {
         TableColumnModel columnModel = _table.getColumnModel();
         _column = columnModel.getColumnIndexAtX(e.getX());
         _row    = e.getY() / _table.getRowHeight();
         Object value;
         JButton button = new JButton();
         MouseEvent buttonEvent;
         if(_row >= _table.getRowCount() || _row < 0 ||
            _column >= _table.getColumnCount() || _column < 0)
           return;
         value = _table.getValueAt(_row, _column);
                          // forward an event to handler...
         }

I have a couple of attempts at this that you may be able to use or at least give you some ideas:
a) Original attempt
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableButton extends JFrame
    public TableButton()
        String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
        Object[][] data =
            {new Date(), "A", new Integer(1), new Double(5.1), new JButton("Delete")},
            {new Date(), "B", new Integer(2), new Double(6.2), new JButton("Delete")},
            {new Date(), "C", new Integer(3), new Double(7.3), new JButton("Delete")},
            {new Date(), "D", new Integer(4), new Double(8.4), new JButton("Delete")}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        final JTable table = new JTable( model )
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
                return getValueAt(0, column).getClass();
            //  Don't edit the button column
            public boolean isCellEditable(int row, int column)
                return column != 4;
        table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
          table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        //  Create button renderer
        TableCellRenderer buttonRenderer = new ButtonRenderer();
        table.setDefaultRenderer(JButton.class, buttonRenderer);
        //  Add table mouse listener
        table.addMouseListener( new ButtonListener(table, 4) );
    public static void main(String[] args)
//        try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
//        catch(Exception e) {}
        TableButton frame = new TableButton();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    class ButtonRenderer extends JButton implements TableCellRenderer
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            JButton button = (JButton)value;
            if (button == null)
                setText( "" );
                getModel().setPressed( false );
                getModel().setArmed( false );
            else
                setText( button.getText() );
                getModel().setPressed( button.getModel().isPressed() );
                getModel().setArmed( button.getModel().isArmed() );
            return this;
     *  1) Creation of class will determine the column to process mouse events on
     *  a) Mouse pressed will determine the row to process and paint pressed button
     *  b) Mouse clicked will do the actual processing
     *  c) Mouse released will paint the normal button
    class ButtonListener extends MouseAdapter
        private JTable table;
        //  Column from the data model to process mouse events on
        private int column;
        //  The table row when the mouse was pressed
        private int row;
        //  The table column when the mouse was pressed
        private int tableColumn;
        //  Repaint the button on mouse released event
        private boolean paintOnRelease;
        ButtonListener(JTable table, int column)
            this.table = table;
            this.column = column;
         *  Repaint button to show pressed state
        public void mousePressed(MouseEvent e)
            //  Make sure the MouseEvent was on the button column
            if ( !buttonColumn(e) ) return;
            //  Repaint the button for the current row/column
            row = table.rowAtPoint( e.getPoint() );
            tableColumn = table.columnAtPoint( e.getPoint() );
            paintButton( true );
            paintOnRelease = true ;
         *  Do table processing on this event
        public void mouseClicked(MouseEvent e)
            //  Make sure the MouseEvent was on the button column
            if ( !buttonColumn(e) ) return;
            //  Only process a single click
            if (e.getClickCount() > 1) return;
            //  Delete current row from the table
            DefaultTableModel model = (DefaultTableModel)table.getModel();
            model.removeRow( this.row );
            //  Row has been deleted, nothing to repaint
            paintOnRelease = false;
         *  Repaint button to show normal state
        public void mouseReleased(MouseEvent e)
            if (paintOnRelease)
                paintButton( false );
            paintOnRelease = false;
        private boolean buttonColumn(MouseEvent e)
            //  In case columns have been reordered, we must map the
            //  table column to the data model column
            int tableColumn = table.columnAtPoint( e.getPoint() );
            int modelColumn = table.convertColumnIndexToModel(tableColumn);
            return modelColumn == column;
        private void paintButton(boolean pressed)
            //  Make sure we have a JButton before repainting
            Object o = table.getValueAt(row, tableColumn);
            if (o instanceof JButton)
                JButton button = (JButton)o;
                button.getModel().setPressed( pressed );
                button.getModel().setArmed( pressed );
                table.setValueAt(button, row, tableColumn);
}b) Latest attempt:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableButton3 extends JFrame
    public TableButton3()
        String[] columnNames = {"Date", "String", "Integer", "Decimal", ""};
        Object[][] data =
            {new Date(), "A", new Integer(1), new Double(5.1), "Delete0"},
            {new Date(), "B", new Integer(2), new Double(6.2), "Delete1"},
            {new Date(), "C", new Integer(3), new Double(7.3), "Delete2"},
            {new Date(), "D", new Integer(4), new Double(8.4), "Delete3"}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable( model )
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
                return getValueAt(0, column).getClass();
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        //  Create button column
        ButtonColumn buttonColumn = new ButtonColumn(table, 4);
    public static void main(String[] args)
        TableButton3 frame = new TableButton3();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    class ButtonColumn extends AbstractCellEditor
        implements TableCellRenderer, TableCellEditor, ActionListener
        JTable table;
        JButton renderButton;
        JButton editButton;
        String text;
        public ButtonColumn(JTable table, int column)
            super();
            this.table = table;
            renderButton = new JButton();
            editButton = new JButton();
            editButton.setFocusPainted( false );
            editButton.addActionListener( this );
            TableColumnModel columnModel = table.getColumnModel();
            columnModel.getColumn(column).setCellRenderer( this );
            columnModel.getColumn(column).setCellEditor( this );
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            if (hasFocus)
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            else if (isSelected)
                renderButton.setForeground(table.getSelectionForeground());
                 renderButton.setBackground(table.getSelectionBackground());
            else
                renderButton.setForeground(table.getForeground());
                renderButton.setBackground(UIManager.getColor("Button.background"));
            renderButton.setText( (value == null) ? "" : value.toString() );
            return renderButton;
        public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column)
            text = (value == null) ? "" : value.toString();
            editButton.setText( text );
            return editButton;
        public Object getCellEditorValue()
            return text;
        public void actionPerformed(ActionEvent e)
            fireEditingStopped();
            System.out.println( e.getActionCommand() + " : " + table.getSelectedRow());
}

Similar Messages

  • Double click on a JTable row.

    I got and run a sample about double click on a JTable and it works fine. This sample defines a TableModel as shown at the end this note.
    On the other hand, I have an application in which I have defined a JTable
    using the DefaultTableModel as follows :
    DefaultTableModel dtm = new DefaultTableModel(data, names);
    JTable table  = new JTable(dtm);  where data and names are String arrays.
    Of course the mouse listener stuffs have been also specified.
    table.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e){
          if (e.getClickCount() == 2){
             System.out.println(" double click" );
         } );Because the difference with the sample was the table model,
    I changed it with the DefaultTableModel class. At this point, the Double click does not work anymore.
    So I gues it should be an option which prevents double click to work.
    I thought of using mousePress() instead of mouseClick(), but it's very dangerous (I tried). . If by error the user clicks twice (instead of only once) the mousePress method is invoked twice for the same entry
    My question is now simple, may I use double click on a JTable with the default table model. If so, what I have to do ?
    Thanks a lot
    Gege
    TableModel dataModel = new AbstractTableModel() {
         public int getColumnCount() { return names.length; }
         public int getRowCount() { return data.length;}
         public Object getValueAt(int row, int col) {return data[row][col];}
         public String getColumnName(int column) {return names[column];}
         public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
         public void setValueAt(Object aValue, int row, int column) {
           data[row][column] = aValue;
         };

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ClickIt extends MouseAdapter
        public void mousePressed(MouseEvent e)
            JTable table = (JTable)e.getSource();
            Point p = e.getPoint();
            if(e.getClickCount() == 2)
                System.out.println("table.isEditing = " + table.isEditing());
            int row = table.rowAtPoint(p);
            int col = table.columnAtPoint(p);
            String value = (String)table.getValueAt(row,col);
            System.out.println(value);
        private JTable getLeftTable()
            final String[] names = { "column 1", "column 2", "column 3", "column 4" };
            final Object[][] data = getData("left");
            TableModel dataModel = new AbstractTableModel() {
                public int getColumnCount() { return names.length; }
                public int getRowCount() { return data.length;}
                public Object getValueAt(int row, int col) {return data[row][col];}
                public String getColumnName(int column) {return names[column];}
                public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
                public void setValueAt(Object aValue, int row, int column) {
                    data[row][column] = aValue;
            JTable table = new JTable(dataModel);
            return configure(table);
        private JTable getRightTable()
            String[] colNames = { "column 1", "column 2", "column 3", "column 4" };
            JTable table = new JTable(new DefaultTableModel(getData("right"), colNames));
            return configure(table);
        private Object[][] getData(String s)
            int rows = 4, cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                for(int col = 0; col < cols; col++)
                    data[row][col] = s + " " + (row*cols + col + 1);
            return data;
        private JTable configure(JTable table)
            table.setColumnSelectionAllowed(true);
            table.setCellSelectionEnabled(true);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.addMouseListener(this);
            return table;
        private JPanel getContent()
            JPanel panel = new JPanel(new GridLayout(1,0,0,5));
            panel.add(new JScrollPane(getLeftTable()));
            panel.add(new JScrollPane(getRightTable()));
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new ClickIt().getContent());
            f.pack();
            f.setVisible(true);
    }

  • Adding JButton into JTable cells

    Hi there!!
    I want to add a JButton into JTable cells.In fact I have got two classes.Class2 has been extended from the AbstractTableModel class and Class1 which is using Class2's model,,,here's the code,,
    Class1
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class Class1 extends javax.swing.JFrame {
       //////GUI specifications
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestTableButton().setVisible(true);
            Class2 model=new Class2();
            jTable1=new JTable(model);
            jScrollPane1.setViewportView(jTable1);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration                  
        private javax.swing.JTable jTable1;
    }Class2
    import javax.swing.table.*;
    public class Class2 extends AbstractTableModel{
        private String[] columnNames = {"A","B","C"};
        private Object[][] data = {
        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];
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         * Don't need to implement this method unless your table's
         * editable.
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
                return false;
         * 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);
    }what modifications shud I be making to the Class2 calss to add buttons to it?
    Can anybody help plz,,,,,??
    Thanks in advance..

    Hi rebol!
    I did search out a lot for this but I found my problem was a bit different,,in fact I want to use another class's model into a class being extended by JFrame,,so was a bit confused,,,hope you can give me some ideas about how to handle that scenario,,I know this topic has been discussed before here many a times and also have visited this link,,
    http://forum.java.sun.com/thread.jspa?threadID=465286&messageID=2147913
    but am not able to map it to my need,,,hope you can help me a bit...
    Thanks .....

  • Changing mouse click behavior on JTable

    Hi everybody,
    The default behavior of a mouse click on a jTable is selection of the cell.
    I would like to change the behavior so when the user clicks once on the cell, the content can be marked and is ready to change. That would give the user the same feeling as Excel.
    Is there any way that I can do this without writing a new mouse/event handler?
    thanks,

    With a call to getSelectionModel() of JTable, you can get a reference to the ListeSelectionModel.
    This is in fact an instance of DefaultListSelectionModel, which allows you to set a new listener object using addListSelectionListener(ListSelectionListener l).
    All you have to do then is implement a custom ListSelectionListener which handles events as you want.
    Unfortunately there isnt going to be a way of avoiding writing a Listener, but this is how you would go about it.
    colr__

  • Multiple JButtons inside JTable cell - Dispatch mouse clicks

    Hi.
    I know this subject has already some discussions on the forum, but I can't seem to find anything that solves my problem.
    In my application, every JTable cell is a JPanel, that using a GridLayout, places vertically several JPanel's witch using an Overlay layout contains a JLabel and a JButton.
    As you can see, its a fairly complex cell...
    Unfortunately, because I use several JButtons in several locations inside a JTable cell, sometimes I can't get the mouse clicks to make through.
    This is my Table custom renderer:
    public class TimeTableRenderer implements TableCellRenderer {
         Border unselectedBorder = null;
         Border selectedBorder = null;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                   boolean hasFocus, int row, int column) {
              if (value instanceof BlocoGrid) {
                   if (isSelected) {
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getSelectionBackground());
                        ((BlocoGrid) value).setBorder(selectedBorder);
                   } else {
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,2,2,2, table.getBackground());
                        ((BlocoGrid) value).setBorder(unselectedBorder);
              return (Component) value;
    }and this is my custom editor (so clicks can get passed on):
    public class TimeTableEditor extends AbstractCellEditor implements TableCellEditor {
         private TimeTableRenderer render = null;
         public TimeTableEditor() {
              render = new TimeTableRenderer();
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
             if (value instanceof BlocoGrid) {
                  if (((BlocoGrid) value).barras.size() > 0) {
                       return render.getTableCellRendererComponent(table, value, isSelected, true, row, column);
             return null;
        public Object getCellEditorValue() {
            return null;
    }As you can see, both the renderer and editor return the same component that cames from the JTable model (all table values (components) only get instantiated once, so the same component is passed on to the renderer and editor).
    Is this the most correct way to get clicks to the cell component?
    Please check the screenshot below to see how the JButtons get placed inside the cell:
    http://img141.imageshack.us/my.php?image=calendarxo9.jpg
    If you need more info, please say so.
    Thanks.

    My mistake... It worked fine. The cell span code was malfunctioning. Thanks anyway.

  • JButton in JTable with custom table model

    Hi!
    I want to include a JButton into a field of a JTable. I do not know why Java does not provide a standard renderer for JButton like it does for JCheckBox, JComboBox and JTextField. I found some previous postings on how to implement custom CellRenderer and CellEditor in order to be able to integrate a button into the table. In my case I am also using a custom table model and I was not able to create a clickable button with any of the resources that I have found. The most comprehensive resource that I have found is this one: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm.
    It works fine (rendering and clicking) when I start it. However, as soon as I incorporate it into my code, the clicking does not work anymore (but the buttons are displayed). If I then use a DefaultTableModel instead of my custom one, rendering and clicking works again. Does anyone know how to deal with this issue? Or does anyone have a good pointer to a resource for including buttons into tables? Or does anyone have a pointer to a resource that explains how CellRenderer and CellEditor work and which methods have to be overwritten in order to trigger certain actions (like a button click)?
    thanks

    Yes, you were right, the TableModel was causing the trouble, everything else worked fine. Somehow I had this code (probably copy and pasted from a tutorial - damn copy and pasting) in my TableModel:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 3) {
                    return false;
                } else {
                    return true;
    }A pretty stupid thing when you want to edit the 3rd column...

  • JButton in JTable Help

    Hi
    I have successfully added a JButton to a table and am able to click on it and when you do it opens up a new window.
    I have set the cellEditor to my new class which performs the actions of a button. I am wanting the new window which opens up to either be presented in the original frame or update the original frame but I have no idea how to do this.
    Can anyone help me?

    I thought it might be hard to understand
    is a main window with information retrieved from a database. When you click on a button in the JTable it opens up a JDialog which edits information in the database. When you submit the changes it closes the second window down and i am wanting it to refresh the original window with the new information in the database.
    Hope this makes sense

  • Adding JButtons to JTable

    Hello all,
    How can I add JButtons to a JTable?
    I found an article that is supposed to show you how to do just that:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I downloaded the code in the article and it works to an extent - I can see the buttons in the table but the buttons seem as if they are disabled :( Since I used this code in my application, I get the same behavior too.
    Is there a bug in the code? Is there a simpler solution? What am I missing?
    Raj

    Thanks. That makes the button clickable. But now the button changes back to it's old value when you click on another cell. I suppose that's because we have 2 buttons, one for rendering and one for editing. So I added a setValueAt(Object value, int row, int column) to MyModel. This works throws class cast exception.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class ButtonInTable extends JFrame {
        JTable t=new JTable(new MyModel());
        public ButtonInTable() {
            this.getContentPane().add(new JScrollPane(t));
            this.setBounds(50,50,300,200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            t.setDefaultEditor(Object.class,new ButtonEditor());
            t.setDefaultRenderer(Object.class,new ButtonRenderer());      
        public static void main(String[] args) {
            ButtonInTable buttonInTable1 = new ButtonInTable();
            buttonInTable1.show();
        class ButtonEditor extends JButton implements TableCellEditor {
            Object currentValue;
            Vector listeners=new Vector();
            public ButtonEditor() {
                            this.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    currentValue=JOptionPane.showInputDialog("Input new value!");
                                    if (currentValue!=null) {
                                        setText(currentValue.toString());
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                currentValue=value;
    //            this.setText(value.toString());
                this.setText( ((JButton)value).getText() );
                return this;
            public Object getCellEditorValue() {
                return currentValue;
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingStopped(ce);
                return true;
            public void cancelCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingCanceled(ce);
            public void addCellEditorListener(CellEditorListener l) {
                listeners.add(l);
            public void removeCellEditorListener(CellEditorListener l) {
                listeners.remove(l);
        class ButtonRenderer extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent
                    (JTable table, Object button, boolean isSelected, boolean hasFocus, int row, int column) {
                return (JButton)button;
        class OldModel extends DefaultTableModel {
            public OldModel() {
                super(new String[][]{{"1","2"},{"3","4"}},new String[] {"1","2"});
        class MyModel extends AbstractTableModel {
            private String[] titles = { "A", "B" };
            private Object[][] summaryTable =
                    { new JButton("11"), new JButton("12") },
                    { new JButton("21"), new JButton("22") }
            public MyModel(){
                super();
            public int getColumnCount() {
                return titles.length;
            public String getColumnName(int col) {
                return titles[col];
            public int getRowCount() {
                return summaryTable.length;
            public Object getValueAt(int row, int col) {
                return summaryTable[row][col];
            public void setValueAt(Object value, int row, int column) {
                summaryTable[row][column] = value;
                fireTableCellUpdated(row, column);
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                return true;
    }

  • Display excel file on clicking JButton

    Hi,
    I have a requirement wherein when the user clicks a JButton, an excel file (which is already present in the app), will open, i.e. Excel 2003 / Xp will get started & display that file.
    Appreciate any help on this.
    Best regards,
    AJ

    Use the Desktop class to open a file with a system default application:
    java.awt.Desktop.getDesktop().open(new File("C:/path/to/whatever.xls"));

  • How to start a function when double-clicked in a JTable

    hi there,
    i got a problem, i want that my JTable reacts when i make a double-click on any row... so that i can start a method that does the things i want to...
    how can i realize that?
    thx anyway
    Errraddicator

    i got a problem, i want that my JTable reacts when i
    make a double-click on any row... so that i can start
    a method that does the things i want to...
    how can i realize that?Easy, just put a mouse listener on it the same way you would a button! In the listener method, you can use
    if ( event.getClickCount()>1 ){
    doWhatever();
    doug

  • How to get jbuttons under jtable and within menu?

    I've developed a menu and will like to display the results of reading a text file in a jtable with jbuttons underneath on the screen somewhere. Is there a way I can display my jbuttons underneath the jtable?, i.e.
    itemno item desc
    1111 bbb
    2222 ccc
    <button> <button>

    Yes.
    In future Swing related questions should be posted into the camickr forum.

  • Reaction on a double click in a JTable

    Hello guys,
    I need to react on a double click on some row in a JTable. I know it must be simple, but I can't find a way to do it!
    Any help will be appreciated.

    Here is a code snipplet out of an application of mine.
    The purpose is to do the same action on double click that would be done by pushing the OK button.
            // Take selected order item on double click.
            this.table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(final MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        Point origin = e.getPoint();
                        int row = OrderSearchDlg.this.table.rowAtPoint(origin);
                        if (row > -1) {
                            okActionPerformed();
            });

  • Double click in a JTable row

    Hi,
    I have the following problem. I would like to have a JTable with single selection (this is ok so far), but I would like it to have the following behaviour.
    If a row is clicked, it becomes selected. If a selected row is clicked again it becomes deselected.
    Does anyone have any suggestions?
    Thnx,
    G

    I am writing about JTree rather than JTable ... because there are no other replies I figured it's better than nothing ...
    This code does the behavior you describe to a JTree.
    (Code snippet copied from JTree javadoc page and modified by me.)
    java.awt.event.MouseListener ml = new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent e) {
    int selRow = tree.getRowForLocation(e.getX(), e.getY());
    if(selRow != -1) {
    if(e.getClickCount() == 1) {
    System.out.println("SINGLE CLICK");
    else if(e.getClickCount() == 2) {
    System.out.println("DOUBLE CLICK");
    tree.clearSelection();
    tree.addMouseListener(ml);
    I put the print statements in to demonstrate that a double-click event actually is a single-click followed by a double-click. Since you didn't sound like you need to do any custom code for the single-click case, this fact probably doesn't affect you.
    I hope I helped
    Mel

  • Click ComboBox in JTable to times before editing ?

    Hi,
    I have a JComboBox in a JTable.
    Now I want to open the ComboBox when
    you click the cell to times.
    There is a method in DefaultCellEditor called
    setClickCountToStart(int).
    But how can I get the reference to the DefaultCellEditor
    from my JTable. There is only a method theTable.getDefaultEditor
    which returns TableCellEditor ?
    Thanx Stephan

    I made it run right in jdk1.3.1 throgh chage the setSelectedItem Method, code is follow:
    public void setSelectedItem(Object item) {
        this.insertItemAt(item, 0);
        if(getItemCount() > 1) {
          this.removeItemAt(1);
        super.setSelectedItem(item);
    }

  • JButton in JTable

    Hello all !
    I want to create a JTable with Cell (class that I will write which extends JButton) in each cell of the table. Cell should contain a state, say 0,1,2 or 3, which dictates the representation of the cell. A representation of a cell contains a background color and an Icon. In addition, I want that if I press the left button of the mouse, the cell will change his state to 1, then to 2 and back to 1, and the right button of the mouse will change the state to 3, then to 4, and back to 3.
    I have tried many ideas based on different examples I found on the Internet, but didn't get what I wanted, and now I'm really confused...
    Can anyone help ?
    I will be grateful for any help !
    Thanks in advance !

    First of all thanks for your wish to help !
    First of all you have no need to extend JTable. You
    just use a DefaultTableModel and add data to the
    model.I tried to use DefaultTableModel, but now I don't see the table at all :)
    Can you explain why ? The code is following:
    public class JCFrame {
         private static void createAndShowGUI() {
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JCTable table = new JCTable();
              frame.add(table);
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(
                   new Runnable() { public void run() { createAndShowGUI(); } });
    public class JCTable extends JTable {
         public JCTable() {
              super(new JCTableModel());               
    public class JCCell extends JButton {
         private int state;
         public JCCell(int initialState) {
              state = initialState;
    public class JCTableModel extends DefaultTableModel {
         private final int numberOfRows = 2;
         private final int numberOfColumns = 3;
         private Object[][] cellsData = new JCCell[numberOfRows][numberOfColumns];          
         public JCTableModel() {
              for (int i = 0; i < numberOfRows; i++)
                   for (int j = 0; j < numberOfColumns; j++)
                        cellsData[i][j] = new JCCell(numberOfRows * i + j);
    }In addition, I don't understand why I don't need to extend JTable. If I want to see a table, I should use JTable somewhere, but where ??
    If you don't want to see the column headers then you
    can use table.setHeader( null );I tried to write this, but the compiler complains that he cannot find symbol method setHeader(...). I neither found this method in Java API. Are you sure about it ?
    And one more question:
    Should the renderer extend JButton ?
    Many thanks !!

Maybe you are looking for

  • How to calculate the total of a calculated column in a list view at the end of the view?

    I have a view with the following columns ProductName, Quantity, Price, Total The total column is a calculated column which is the product of quantity and price. I want to place the sum of the total column by the end of the list view. I can do this wi

  • Regarding java mapping failure

    Hai all   Iam Ajay , here i would like to create XML Tree using DOM Parser. In the java Program i need to import "com.sap.aii.mapping.*" library. Unfortunately i don't have that. could you suggest me where do i import the jar file which includes the

  • How to do a group video-call (more than 2)?

    Hi, Does anyone know how to do group (more than 2) video calls with facetime?

  • My PDF bookmarks are displaying weirdly

    My PDF bookmarks are displaying weirdly: they are displaying in blank boxes (apart from the title), rather than as neat single line (or wrapped text) boxes. Also, the left-hand side of the Bookmark column is blank, the bookmark 'thumbnails' are way o

  • Essbase server freeze - reply urgent

    Hi All,<BR><BR>We are facing a very serious issue with Essbase 6.5.5 since last couple of months. The problem is whenever we tried to copy database or application, the Essbase server gets freeze after copying. When it happens, every time we need to k