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

Similar Messages

  • 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 .....

  • 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 !!

  • JButtons in JTable

    I wish to add JButtons to cells in a JTable using a loop. Using
    table.getColumn("Load to monitor").setCellRenderer(new ButtonRenderer());
    table.getColumn("Load to monitor").setCellEditor(new ButtonEditor(new JCheckBox()));
    adds buttons to all cells in the Load to monitor column. I want to add the buttons one by one in order to use a setName function for each button
    Any help greatly appreciated.

    Don't cross-post. This is a Swing related question and has already been posted in the Swing forum:
    : http://forum.java.sun.com/thread.jspa?threadID=678170

  • JTable - Help with column names and rowselection

    Hi,
    Is there anyone that can help me. I have successfully been able to load a JTable from an MS access database using vectors. I am now trying to find out how to hardcode the column names into the JTable as a string.
    Can anyone please also show me some code on how to be able update a value in a cell (from ''N'' to ''Y'') by double clicking on that row.
    How can I make all the other columns non-editable.
    Here is my code:
         private JTable getJTable() {
              Vector columnNames = new Vector();
    Vector data = new Vector();
    try
    // Connect to the Database
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // String url = "jdbc:odbc:Teenergy"; // if using ODBC Data Source name
    String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Documents " +
              "and Settings/Administrator/My Documents/mdbTEST.mdb";
    String userid = "";
    String password = "";
    Class.forName( driver );
    Connection connection = DriverManager.getConnection( url, userid, password );
    // Read data from a table
    String sql = "select * from PurchaseOrderView";
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery( sql );
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    // Get column names
    for (int i = 1; i <= columns; i++)
    columnNames.addElement( md.getColumnName(i) );
    // Get row data
    while (rs.next())
    Vector row = new Vector(columns);
    for (int i = 1; i <= columns; i++)
    row.addElement( rs.getObject(i) );
    data.addElement( row );
    rs.close();
    stmt.close();
    catch(Exception e)
    System.out.println( e );
              if (jTable == null) {
                   jTable = new JTable(data, columnNames);
                   jTable.setAutoCreateColumnsFromModel(false);
                   jTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
                   jTable.setShowHorizontalLines(false);
                   jTable.setGridColor(java.awt.SystemColor.control);
                   jTable.setRowSelectionAllowed(true);
                   jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
                   jTable.setShowGrid(true);     
              return jTable;
         }

    this method has a default behavior to supply exactly what you're seeing: column names consisting of the capitalized letters, "A", "B", "C".Thanks Pete, had seen that but never really thought about it... about 10 days ago somebody needed to obtain Excel column names, I'd offered a rigorous solution and now see it would have been shorter and simpler (if a little heavier) to extend DefaultTableModel and provide the two additional methods needed (getOffsetCol and getColIndex).
    Not much of a difference in LOC but certainly more elegant ;-)
    Darryl

  • JTable help - trying to copy/paste a row in a JTable

    Hello,
    Geez, JTable is such a pain..... I am trying copy a range of rows within a JTable using an Abstract Table Model). I need to use this Abstract model as I have a custom String Tokenizing routine which accesses a flat text file which is my "table" so-to-speak.....
    The sequence of events are:
    1. Highlight the selected rows via the Mouse
    2. Select "Copy" from a menu pull down which then runs
    my copy method which resides in my abstract table model,which properly figures out which cells I need to copy (see below code), and opens up new rows at the bottom
    of the JTable.
    I am trying to automatically take those selected cells and then paste them into the opened up rows at the end of the table when choosing "Paste" from the menu.
    Here is the copy method, and the code that calls it from my main application. I am having a bit of trouble trying to figure out the Paste routine which is where I need help.
    Sorry if this is a bit redundant, but I've been struggling with it...... I know that the System Clipboard is available, but I just cant get that to work for me...
    Does 1.4.1 have an "easy" way to do this so I don't have to re-invent the wheel ????
    Thanks in advance
    From my main app:
    private void updateTheFiles(String updateType)
    // Determine which model we are working with //
    currmodel = (DataFileTableModel)vec.elementAt(tabnum) ;
    System.out.println("File = " + fileNameArray[tabnum] );
    if (updateType == "Save") {     
    System.out.println("updateType = " + updateType );
    Object tfs = new TextFileSaver(currmodel,fileNameArray[tabnum],"Pipe",true) ;}
    if (updateType == "Insert") {
    System.out.println("updateType = " + updateType );
    int a = currmodel.getColumnCount() ;
    Object [] aRow = new Object [a];
    currmodel.addRow(aRow); }
    if (updateType == "Delete") {
    System.out.println("updateType = " + updateType );
    currmodel.deleteRows(startRowToBeDeleted, endRowToBeDeleted); }
    if (updateType == "Copy") {
    System.out.println("updateType = " + updateType );
    ----> currmodel.copyRows(startRowToBeDeleted, endRowToBeDeleted);
    // if (updateType == "Paste") {
    // System.out.println("updateType = " + updateType );
    // TablePaste tp = new TablePaste(userTable) ;
    // if (updateType == "Find") {
    // System.out.println("updateType = " + updateType );
    // Object fnd = new FindReplace() ; }
    // currmodel.copyRows(startRowToBeDeleted, endRowToBeDeleted); }
    Table Model:
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.io.* ;
    import java.util.* ;
    import java.lang.* ;
    public class DataFileTableModel extends AbstractTableModel {
    //public class DataFileTableModel extends DefaultTableModel {
    protected Vector data;
    protected Vector columnNames ;
    protected Vector copyVec ;
    protected String datafile;
    public DataFileTableModel(String f){
    datafile = f;
    initVectors();
    public void initVectors() {
    String aLine ;
    data = new Vector();
    columnNames = new Vector();
    try {
    FileInputStream fin = new FileInputStream(datafile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
    // extract column names
    StringTokenizer st1 =
    new StringTokenizer(br.readLine(), "|");
    while(st1.hasMoreTokens())
    columnNames.addElement(st1.nextToken());
    // extract data
    while ((aLine = br.readLine()) != null) {
    StringTokenizer st2 =
    new StringTokenizer(aLine, "|");
    while(st2.hasMoreTokens())
    data.addElement(st2.nextToken());
    br.close();
    catch (Exception e) {
    e.printStackTrace();
    public int getRowCount() {
    return data.size() / getColumnCount();
    public int getColumnCount(){
    return columnNames.size();
    public String getColumnName(int columnIndex) {
    String colName = "";
    if (columnIndex <= getColumnCount())
    colName = (String)columnNames.elementAt(columnIndex);
    return colName;
    public Class getColumnClass(int columnIndex){
    return String.class;
    public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
    public Object getValueAt(int rowIndex, int columnIndex) {
    return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    data.setElementAt(aValue, (rowIndex * getColumnCount())+columnIndex) ;
    fireTableCellUpdated(rowIndex, columnIndex);
    public void addRow(Object[] aRow) {
    for (int i=0; i < aRow.length; i++)
    data.add(aRow);
    int size = getRowCount();
    fireTableRowsInserted(size-1,size-1);
    public void deleteRows(int startRow, int endRow)
    int tempRow = 0;
    int actualRows = 0;
    if (endRow < startRow)
    tempRow = endRow ;
    endRow = startRow ;
    startRow = tempRow ; }
         if (startRow < 0 || endRow > getRowCount())
         return;
         actualRows = (endRow - startRow) + 1 ;
         // determine the starting point (cell) to start deleting at //
         int colCount = getColumnCount() ;
         int cell = startRow * colCount ;
         // determine the total number of cells to delete //
         int totColCount = (getColumnCount() * actualRows) ;
         for (int d = 0; d < totColCount; d++)
         data.remove(cell) ;
    fireTableRowsDeleted(startRow,endRow) ;
    public void copyRows(int cStartRow, int cEndRow)
    System.out.println("Startrow = " + cStartRow) ;
    System.out.println("Endrow = " + cEndRow) ;
    int cTempRow = 0;
    int cActualRows = 0;
    if (cEndRow < cStartRow)
    cTempRow = cEndRow ;
    cEndRow = cStartRow ;
    cStartRow = cTempRow ; }
         if (cStartRow < 0 || cEndRow > getRowCount())
         return;
         cActualRows = (cEndRow - cStartRow) + 1 ;
         // determine the starting (cell) to start copying from //
         int cStartCell = cStartRow * getColumnCount() ;
         // determine the total number of cells to copy //
         int cTotCells = (getColumnCount() * cActualRows) ;
         // determine the ending cell //
         int cEndCell = (cStartCell + cTotCells) - 1 ;
         System.out.println("Start Cell = " + cStartCell) ;
         System.out.println("End Cell = " + cEndCell) ;
         System.out.println("Total Cells = " + cTotCells) ;     
         // Now we have to load the empty rows with the copied data //
         System.out.println("getrowcount = " + getRowCount()) ;
         // Open up empty rows where the copied data will reside //
         for (int ci = 0 ; ci < cActualRows ; ci++ )
         Object [] cRow = new Object [getColumnCount()] ;
         addRow(cRow) ;
         int newRowStart = (getRowCount() - cActualRows) ;
         int newRowEnd = getRowCount() - 1 ;
         System.out.println("new row start = " + newRowStart) ;
         System.out.println("new row end = " + newRowEnd ) ;

    Hi Veeru,
    I like to copy and paste in Excel too, so just do it!
    This forum is intended to help on specific problems. As you only told us what you like we can offer no help.
    But you may search the forum for all those other Excel related threads to find hints/examples/thoughts on this...
    Message Edited by GerdW on 01-12-2010 01:06 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Adding Image in JTable - help needed(Urgent).

    Hai Friends,
    i want to add two icon in the cells of JTable... i dont know where am going wrong... the icon is not getting displayed in the cell but instead if i double click the cell the name of the icon is displayed in editable mode... any suggestion...
    this is my code... i got this from the forum only... but tis not working....
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("juggler.ico"), "Copy"},
                   {new ImageIcon("favicon.gif"), "Add"},
              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)
          System.out.println("getValueAt(0, column)"+getValueAt(0, 0));
                        return getValueAt(0, 0).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }Urgent... pls help...
    Regards,
    Ciya.

    Hai Chris,
    Thanks for ur reply,
    Now Its throwing null pointer exception in the URL....
    Can u pls look into d code and tell me pls...
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.net.URL;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    public class MyIcon extends JPanel
      private JScrollPane jScrollPane1 = new JScrollPane();
      private JTable jTable1;
      private GridBagLayout gridBagLayout1 = new GridBagLayout();
      public MyIcon()
        try
          jbInit();
        catch(Exception e)
          e.printStackTrace();
      private void jbInit() throws Exception
        this.setLayout(gridBagLayout1);
        jTable1 = new JTable(new AbstractTableModel()
         URL lURL = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
          URL lURL2 = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
        Object[][] data =
            {new ImageIcon(lURL), "Copy"},
            {new ImageIcon(lURL), "Add"},
          public int getRowCount()
            return 2;
         public int getColumnCount()
           return 2;
         public Object getValueAt(int row, int column)
           return data[row][column];
        jTable1.getColumnModel().getColumn(0).setCellRenderer(new Renderer());
        jScrollPane1.getViewport().add(jTable1, null);
        this.add(jScrollPane1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(60, 20, 125, 25), -97, -287));
      public static void main(String a[])
        MyIcon c = new MyIcon();
        JFrame f = new JFrame();
        f.getContentPane().add(c);
        f.setSize(400,400);
        f.setVisible(true);
      class Renderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    setIcon((ImageIcon) value);
    return this;
    }Ciya...

  • Column width in JTables.Help needed!!!!

    Hi
    I am trying to print out a JTable and have had a few problems along the way but have managed to solve them all so far apart from this one. When the JTable is shown on screen it doesn't make the columns wide enough . I ahev managed to find some code from these forums but it doesnt resize correctly if the Column headings contain more text than any of the data (If you know what i mean). Below is the code i am using
    public void sizeAllColumnsToFitData (JTable table)  {
        for (int col = 0; col < table.getColumnCount (); col++)  {
          TableColumn curColumn = table.getColumn (table.getColumnName (col));
          if (curColumn == null)
            continue; // not a valid column skip
    //  Translate to the model
          int modelColumn = curColumn.getModelIndex ();
    //  Loop for all rows in this column looking for the widest piece of data
          int maxColumnWidth = 0;
          for (int row = 0; row < table.getRowCount(); row++)  {
            TableCellRenderer curCellRenderer = table.getCellRenderer (row, modelColumn);
            Object value = table.getValueAt (row, modelColumn);
            Component curRenderComponent = curCellRenderer.getTableCellRendererComponent(table, value, true, true, row, modelColumn);
            Dimension cellDimension = curRenderComponent.getPreferredSize ();
            if (cellDimension.width > maxColumnWidth)
              maxColumnWidth = cellDimension.width;
    //  Set the column width to fit the maximum
          Dimension cellSpacing = table.getIntercellSpacing ();
          curColumn.setPreferredWidth (maxColumnWidth + (cellSpacing != null ? cellSpacing.width : 1));
      }I pass my table into here and it works fine apart from in doesnt take into consideration the size of the headings. Please Help ME!!!!

    java.lang.NullPointerException
         at database_testing.SLAMS.sizeAllColumnsToFitData(SLAMS.java:473)
         at database_testing.SLAMS.getInfo(SLAMS.java:364)
         at database_testing.SLAMS.getInfo_actionPerformed(SLAMS.java:434)
         at database_testing.SLAMS_getInfo_actionAdapter.actionPerformed(SLAMS.java:527)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5134)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)Also i think it may have something to do with my headerRenderer being null cus if i replace the line TableCellRenderer headerRenderer = curColumn.getHeaderRenderer(); with TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); then it doesnt come up with an error but only increase the size of the coluns (where neccessary by 2 characters)

  • 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...

  • JTable help:- Setting Table Header and scrollbar

    hi
    everybody.
    i have create a table which is getting the data from URL Connection by parsing the XML file.
    All is working fine but the only problem is that i am not able to set the column headers.
    and also want to set scrollbars to my table because the data in my table is long.
    i have tried with JTableHeader and TableModel, but i am confused with it.
    so can anybody solve my problem.
    i am sending my code for creating table, and also sending the file from which the data is retrieved.
    please go through the code and reply me.
    If u are not able to parse the xml file than simply removed that part and using the QUERYResp.txt which i have attached, because i think the URL which i am using will not be accessed other than my network
    waiting for reply.
    //SelectPrivilege.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.w3c.dom.*;
    import java.net.*;
    import java.util.*;
    public class SelectPrivilege extends JFrame implements ActionListener
         JFrame frame;
         JTable table;
         JPanel buttonpanel;
         JButton openbutton,donebutton;
         String strclassname,strmembertype,strpasswordduration,strclassdescription;
        private boolean ALLOW_ROW_SELECTION = true;
        ListSelectionModel rowSM;
         Document document;
         Node node;
         NodeList employees,children;
         Element employee;
         String inputline,strSuccess;
         URL url;
         URLConnection connection;
         FileInputStream fis;
         DataInputStream dis;
         String objid,classname,membertype,passwordexp,description,finalstring;
         StringTokenizer st;
         String strurl = "<CLFAPP><CLFYAPP_MSG_TYPE_MSG_TYPE>QUERY</CLFYAPP_MSG_TYPE_MSG_TYPE><TABLE>PRIVCLASS</TABLE><FIELDS>OBJID,CLASS_NAME,MEMBER_TYPE,PSWRD_EXP_PER,DESCRIPTION</FIELDS><FILTER></FILTER></CLFYAPP>";
         public SelectPrivilege()
              JFrame.setDefaultLookAndFeelDecorated(true);
              frame = new JFrame("Select Privilege Class");
              try
                   url = new URL("http://10.8.54.55:7002/RILClarifyAppRequest?XML=" + strurl);
                   connection = url.openConnection();
                   BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                   FileOutputStream out = new FileOutputStream("QUERYResp.xml");
                   PrintStream p = new PrintStream(out);
                   while ((inputline = reader.readLine()) != null)
                        System.out.println("Response Received......");
                        p.println(inputline);
                   p.close();
                   reader.close();
              catch(MalformedURLException e)
                   System.out.println(e.getCause());
              catch(IOException e)
                   System.out.println(e.getCause());
              //Parsing XML
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              try
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   document = builder.parse(new File("QUERYResp.xml"));
                   node = document.getDocumentElement();
                   employees = document.getElementsByTagName("RECORD");
                   FileOutputStream out = new FileOutputStream("QUERYResp.txt");
                   PrintStream p = new PrintStream(out);
                   for(int i = 0; i < employees.getLength(); i++)
                        final Element employee = (Element)employees.item(i);
                        p.print(getValueOf(employee,"OBJID"));
                        p.print("#");
                        p.print(getValueOf(employee,"CLASS_NAME"));
                        p.print("#");
                        p.print(getValueOf(employee,"MEMBER_TYPE"));
                        p.print("#");
                        p.print(getValueOf(employee,"PSWRD_EXP_PER"));
                        p.print("#");
                        p.print(getValueOf(employee,"DESCRIPTION"));
                        p.print("#@");
                        //p.close();
                        objid = getValueOf(employee,"OBJID");
                        classname = getValueOf(employee,"CLASS_NAME");
                        membertype = getValueOf(employee,"MEMBER_TYPE");
                        passwordexp = getValueOf(employee,"PSWRD_EXP_PER");
                        description = getValueOf(employee,"DESCRIPTION");
              catch(SAXException sxe)
                   Exception x = sxe;
                   if(sxe.getException() != null)
                        x = sxe.getException();
                   x.printStackTrace();
              catch(ParserConfigurationException pce)
                   pce.printStackTrace();
              catch(IOException ioe)
                   ioe.printStackTrace();
              catch(NullPointerException npe)
                   System.out.println(npe.getCause());
              table();
              buttonpanel = new JPanel();
              buttonpanel.setLayout(new FlowLayout());
              openbutton = new JButton("Open");
              donebutton = new JButton("Done");
              donebutton.setMnemonic('d');
              buttonpanel.add(openbutton);
              buttonpanel.add(donebutton);
              openbutton.addActionListener(this);
              donebutton.addActionListener(this);
              Container contentpane = getContentPane();
              frame.setContentPane(contentpane);
              contentpane.setLayout(new BorderLayout());
              contentpane.add(table.getTableHeader(),BorderLayout.PAGE_START);
              contentpane.add(table,BorderLayout.CENTER);
              contentpane.add(buttonpanel,BorderLayout.SOUTH);
              frame.setSize(500,400);
              frame.setVisible(true);
         static String getValueOf (Element element, String tagname)
              final NodeList children = element.getElementsByTagName(tagname);
              if (children.getLength() == 0) { return null; }
                   return concat(children, new StringBuffer()).toString();
         static StringBuffer concat (NodeList nodelist, StringBuffer buffer)
              for (int index = 0, length = nodelist.getLength(); index < length; index++)
                   final Node node = nodelist.item(index);
                   switch (node.getNodeType())
                        case Node.CDATA_SECTION_NODE: buffer.append(node.getNodeValue()); break;
                        case Node.ELEMENT_NODE: concat(node.getChildNodes(), buffer); break;
                        case Node.TEXT_NODE : buffer.append(node.getNodeValue()); break;
              return buffer;
         public void table()
              try
                   fis = new FileInputStream("QUERYResp.txt");
                   dis = new DataInputStream(fis);
                   finalstring = dis.readLine();
              catch(IOException e)
              st = new StringTokenizer(finalstring, "@");
              table = new JTable(st.countTokens() + 1,5);
              table.setValueAt("OBJID",0,0);
              table.setValueAt("CLASS NAME",0,1);
              table.setValueAt("MEMBER TYPE",0,2);
              table.setValueAt("PASSWORD DURATION",0,3);
              table.setValueAt("DESCRIPTION",0,4);
              int count = 0,cnt=0;
              StringTokenizer st1 = null;
              try
                   while(st.hasMoreTokens())
                        st1 = new StringTokenizer(st.nextToken(),"#");
                        cnt=0;
                        while(st1.hasMoreTokens())
                             table.setValueAt(st1.nextToken(),count,cnt++);
                        count++;
                        st1=null;
              catch(Exception e)
                   e.printStackTrace();
              //JTableHeader header = table.getTableHeader();
              table.setPreferredScrollableViewportSize(new Dimension(200,500));
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            if(ALLOW_ROW_SELECTION)
                 rowSM = table.getSelectionModel();
                 rowSM.addListSelectionListener(new ListSelectionListener(){
                            public void valueChanged(ListSelectionEvent e)
                                 ListSelectionModel row = (ListSelectionModel)e.getSource();
                                 if (row.isSelectionEmpty() == true)
                                    System.out.println("No rows are selected.");
                                else
                                     if (e.getValueIsAdjusting())
                                          return;
                                         int selectedRow = row.getMinSelectionIndex();
                                         System.out.println("Row " + selectedRow + " is now selected.");
                 JScrollPane scrollpane = new JScrollPane(table);
         public void createprivilegeclassdetails()
              PrivilegeClassDetails privilegeclassdetailsobj = new PrivilegeClassDetails();
              privilegeclassdetailsobj.frame.setSize(400,400);
              privilegeclassdetailsobj.frame.setVisible(true);
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equalsIgnoreCase("done"))
                   System.out.println("SelectPrivilege Window Closed");
                   frame.dispose();
              if(str.equalsIgnoreCase("open"))
                   System.out.println("here");
                   createprivilegeclassdetails();
         public static void main(String a[])
              new SelectPrivilege();
    Copy the whole line if ur saving this in a file, as it is a string
    //QUERYResp.txt
    268435457#CSR#Employees#0#Customer Support Representative#@268435458#Hotline Engineer#Employees#0#Hotline Engineer#@268435459#Product Specialist#Employees#0#Product Specialist#@268435460#Senior Product Specialist#Employees#0#Senior Product Specialist#@268435461#Field Engineer#Employees#0#Field Engineer#@268435462#Support Manager I#Employees#0#Support Manager I#@268435463#Support Manager II#Employees#0#Support Manager II#@268435464#Development Engineer#Employees#0#Development Engineer#@268435465#Development Manager#Employees#0#Development Manager#@268435466#QA Engineer#Employees#0#QA Engineer#@268435467#QA Manager#Employees#0#QA Manager#@268435468#Technical Writer#Employees#0#Technical Writer#@268435469#Technical Publications Manager#Employees#0#Technical Publications Manager#@268435470#Site Configuration Manager#Employees#0#Site Configuration Manager#@268435471#Product Administrator#Employees#0#Product Administrator#@268435472#Technical Product Administrator#Employees#0#Technical Product Administrator#@268435473#Contract Specialist#Employees#0#Contract Specialist#@268435474#System Administrator#Employees#90#System Administrator#@268435475#Submitter#Contacts#0#Submitter#@268435476#Viewer#Contacts#0#Viewer#@268435477#Inventory Specialist#Employees#0#Inventory Specialist#@268435478#Logistics Manager#Employees#0#Logistics Manager#@268435479#Sales Representative#Employees#0#Sales Representative#@268435480#Marketing Representative#Employees#0#Marketing Representative#@268435481#Sales Manager#Employees#0#Sales Manager#@268435482#Offline User#Employees#0#Privilege Class for use with ClearEnterprise Traveler#@268435483#Call Center Agent#Employees#30#Call Center Agent#@268435484#Call Center Manager#Employees#0#Call Center Manager#@268435485#Customer Service Agent#Employees#0#Customer Service Agent#@268435486#Telemarketing Agent#Employees#0#Telemarketing Agent#@268435487#Telesales Agent#Employees#0#Telesales Agent#@268435488#Telesales Manager#Employees#0#Telesales Manager#@268435489#Avaya_Users#Employees#0#Privilege Class for Avaya. Only Clear Call Center Application Enabled.#@268435490#Account Manager#Employees#0#Account Manager for Accounts#@268435491#Account Executive#Employees#30#Account Executive for Accounts#@268435492#Pre Sales Tech Executive#Employees#0#Pre Sales Technical Executive#@268435493#Pre Sales Tech Team Lead#Employees#0#Pre Sales Technical Team Leader#@268435494#Post Sales Tech Executive#Employees#0#Post sales technical executive#@268435495#Post Sales Commercial Executive#Employees#0#Post sales commercial executive#@268435496#Vertical Domain Expert#Employees#0#Vertical Domain Expert#@268435497#Supervisor#Employees#0#Supervior who approves the billing adjustments#@268435498#RA#Employees#0##@268435499#Configuration#Employees#90#Privilege Class for Clarify Configurators#@268435500#FO Online Agent#Employees#0#Testing#@268435501#OTAF Remote Funcionality#Employees#0##@268435502#Sr.Manager CC#Employees#0#Customization for phase1 RUNS (1a).#@268435503#FO Online Unit - Agent #Employees#0#Customization for phase1 RUNS (1).#@268435504#FO Online - Agent (outbound)#Employees#0#Customization for phase1 RUNS (1b).#@268435505#Incoming mail unit manager#Employees#0#Customization for phase1 RUNS (2).#@268435506#Save team agent#Employees#0#Customization for phase1 RUNS (3).#@268435507#Save team supervisor#Employees#0#Customization for phase1 RUNS (4).#@268435508#Technical suport agent#Employees#0#Customization for phase1 RUNS (5).#@268435509#Technical suport supervisor#Employees#0#Customization for phase1 RUNS (6).#@268435510#Webstore Agents#Employees#0#Customization for phase1 RUNS (7).#@268435511#FO Offline Unit (Reg)- Supervisor#Employees#0#Customization for phase1 RUNS (8).#@268435512#Head C. Service (Circles)#Employees#0#Customization for phase1 RUNS (8a).#@268435513#Revenue Assurance#Employees#0#Customization for phase1 RUNS (9).#@268435514#Manager CC#Employees#0#Customization for phase1 RUNS (1a).#@268435515#FO Offline Unit - Agent at Contact Centre#Employees#0#Customization for phase1 RUNS (1).#@268435516#Telesales unit agent#Employees#0#Customization for phase1 RUNS (1).#@268435517#Incoming mail unit agent#Employees#0#Customization for phase1 RUNS (1).#@268435518#Telesales supervisor#Employees#0#Customization for phase1 RUNS (2).#@268435519#FO Online Unit - Supervisor#Employees#0#Customization for phase1 RUNS (2).#@268435520#FO Offline Unit (CC) - Supervisor#Employees#0#Customization for phase1 RUNS (2).#@268435521#TT unit agent#Employees#0#Customization for phase1 RUNS (5).#@268435522#TT unit supervisor#Employees#0#Customization for phase1 RUNS (6).#@268435523#Pos Agents#Employees#0#Customization for phase1 RUNS (7).#@268435524#FO Offline Unit - Regions#Employees#0#Customization for phase1 RUNS (7).#@268435525#Service fulfillment unit agent#Employees#0#Customization for phase1 RUNS (7).#@268435526#Sales Executives (Regions)#Employees#0#Customization for phase1 RUNS (7).#@268435527#Webstore Manager#Employees#0#Customization for phase1 RUNS (8).#@268435528#Service fulfillment unit manager#Employees#0#Customization for phase1 RUNS (8).#@268435529#Network#Employees#0#Customization for phase1 RUNS (9).#@268435530#After Sales#Employees#0#Customization for phase1 RUNS (9).#@268435531#Handsets#Employees#0#Customization for phase1 RUNS (9).#@268435532#Portal#Employees#0#Customization for phase1 RUNS (9).#@268435533#GIS#Employees#0#Customization for phase1 RUNS (9).#@268435534#Logistics#Employees#0#Customization for phase1 RUNS (9).#@268435535#Data Services#Employees#0#Customization for phase1 RUNS (9).#@268435536#Production Support#Employees#0#Since it is possible to temper the data form the Clarify GUI , restrict all access to users except for the minimal in order to control the env.#@268435537#Webstore Users#Employees#0##@268435539#IN_CSR#Employees#0#Privilege Class for Prepaid CSR's#@268435540#Configuration_Maha#Employees#0#Privilege Class for Clarify Configurators#@268435541#test privilege class#Employees#0##@268435542#PS_TEST#Employees#0##@268435543#TEST SACHIN#Employees#0#SACHIN TEST#@268435544#Supervisor1#Employees#300#Supervise and monitor agents#@268435545#Call Center Adminstrator#Employees#0#Call Center Admin Priv#@268435546#siva_test#Employees#0#new privilege class for test purpose#@268435547#PREPAID PCO#Employees#0#For PREPAID PCO#@268435548#santo_test#Employees#0#new privilage class for test#@

    Don't start by writing a 100 line program to test a component you don't know how to use. Start by writing a 10 line program. This is all you need:
              String[] columnNames = {"Date", "String", "Centered", "Integer", "Boolean"};
              Object[][] data =
                   {new Date(), "A", "A", new Integer(1), new Boolean(true)},
                   {new Date(), "B", "B", new Integer(2), new Boolean(false)},
                   {new Date(), "C", "C", new Integer(10), null},
                   {new Date(), "D", "D", new Integer(4), new Boolean(false)}
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              model.addTableModelListener( this );
              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();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );

  • Columns in JTable, Help!

    Hello There,
    I have two question about the JTable in Java:
    1. How can i set a column width? I want to have one column widder than the other and not editable at runtime.
    2. How can i have multiple lines (block of data/small paragraph) in one cell? because whenver i write a 3 new lines of data in a cell the JTable converts it cont. line.
    Please Help!!

    Here there is a JTable where 3 colums are being resized
    TableColumn column1 = null;
                   for (int i = 0; i < 3; i++) {
                       column1 = table1.getColumnModel().getColumn(i);
                       if (i == 0) {
                           column1.setPreferredWidth(20);
                       } else {
                            if (i == 1){
                                 column1.setPreferredWidth(160);
                            else
                                 column1.setPreferredWidth(80);
                   }

  • 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.

  • JTable Help To add a column

    Hi friends
    I hava a problem:-
    IN SHORT I WANT TO ADD A COLUMN TO THE JTABLE. Please read to understand the problem...
    I made a class called clsViewUsers which implements AbstractTableModel. This class fetches data and this data is put in the JTable with the constructor JTable(javax.swing.table.TableModel dm).
    Now I want to add a column to the table without disturbing the TableModel.
    I tried JTable.addColumn(javax.swing.table.TableColumn aColumn).
    I made TableColumn UserStatusColumn = new TableColumn();
    This TableColumn class has a function called setCellRenderer(TableCellRenderer aRenderer). This function takes a TableCellRenderer.
    I made a class which implements this TableCellRenderer. This class compiles well but when this returns the java.awt.Component class to setCellRenderer(TableCellRenderer aRenderer)(Function above). Then it gives compile error as setCellRenderer(javax.swing.table.TableCellRenderer) in javax.swing.table.TableColumn cannot be applied to (java.awt.Component).
    IN SHORT I WANT TO ADD A COLUMN TO THE JTABLE.
    Please help
    Vishwajeet Wadhwa

    You can use a vector called columNames to store the column names and create a method like
    public void addColumn(String columnName) {
    columnNames.add(columnName);
    you can make your model implement an interface that has a method for adding columns like
    public interface ChangeableColumn{
    public void addColumn(String columnName);
    and have some other object like a panel with a button hold a reference to the TableModel which implements the interface
    somePanel.addChangeableColumnListener(ChangeableColumListener tablemodel){
    this.columnListener = tablemodel;
    and the panel can have a method called addColumn(String columnName){}
    that will called the method in the interface which will be implemented in the model
    something like that maybe

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

Maybe you are looking for

  • Hard drive won't mount after running disk utility repair

    I have an iMac with a 320gb hard drive. It will not mount. The small horible wheel started sining so I retared. It could not find the start-up disk. I restared with the CD, after doing this twice the disk was visible in disk untility. I have ran this

  • Help with bank program

    Hi all, i have created a basic bank program that uses a database to access data etc. One of my programs is called MainMenu which is my main class and another one called AccMaster. When I call for the AccMaster in MainMenu I keep getting an error in t

  • Setting initialcontext timeout

    Hello I was wondering if I could set the timeout period for creating InitialContext? For example if my server is down and I am trying to get Initial Context from this server It takes about 8 minutes to timeout and throws ConnectionException. I am usi

  • HELP IN KEITHLEY output source PROGRAM!(how to change GPIB to serial port)

    As the topic suggest,can anyone help me in changing from GBIP to serial port?The file is found inside the .lib that i attached. filename:2400 swI Linear Stair MeasV - LED.vi thanks! Attachments: KEITHLEY PROGRAM.zip ‏434 KB

  • How create a container for diagram ERD (Oracle Design)

    Hi, I need help it will create an ERD but pops up a screen asking me to choose "Select the deafult container for this diagram." And the choice is all in white registering wanted one but do not know where to register. Can anyone help me .. It is urgen