Jtable in the cell of parent jtable

hi,
i wans to make jtable whose all cell's contains jtable and all of these jtables should dynamically get different datas .suppose i needs to create a parent 10*3 jtable,now all the 30 cells again contains jtable of 1*2 and all these 1*2 jtables contains different datas at runtime how can i do that plz sujjest me.

Implement the TableCellRenderer interface to return a JTable.
How to use tables: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
Also worth asking yourself whether you really are better off with tables within tables, or if it's more appropriate to simply use a 10x6 table. Might be one, might be the other.

Similar Messages

  • How to restrict the cell selection in JTable based on cell contents...

    Hi all,
    I have some problem related to table cell selection.
    I have a table that represets the calendar of some month and year.
    I have the restriction that at one time only one cell could be selected.
    Now i want the cell seletion like this,
    I want only those dates to be selected if that date is after 'today'.
    that is I want to restrict the selection of previous dates.
    how can i do this.
    I have overridden the table methods like this, still no use.
    table = new JTable(model) {
    setOpaque(false);
    setSurrendersFocusOnKeystroke(false);
    setRowHeight(20);
    JTableHeader header = getTableHeader();
    header.setOpaque(false);
    getTableHeader().setReorderingAllowed(false);
    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    getTableHeader().setResizingAllowed(false);
    setCellSelectionEnabled(true);
    setFocusable(true);
    setBackground(new Color(247, 251, 255));
    setFont(newFont);
    public boolean isCellEditable(int row, int col) {
    return false;
    public boolean isCellSelected(int row, int col) {
    int r = getSelectedRow();
    int c = getSelectedColumn();
    String val = (String)getValueAt(r,c);
    Calendar cal = Calendar.getInstance();
    cal.set(currentYear+1900, month,Integer.parseInt(val));
    Date d = cal.getTime();
    Date currentDate = new Date();
    if (d.before(currentDate)) {
         return false;
    } else {
         return true;
    Someone please help...
    -Soni

    Try overriding the changeSelection(....) method of JTable.
    public void changeSelection(int row, int column, boolean toggle, boolean extend)
         if (d.after(currentDate)
              super.changeSelection(row, column, toggle, extend);
    }

  • JTable :Setting the cell renderer overrides default behaviour

    I have a class renderer as shown below.
    I would like to apply this renderer to my cells in my JTable (see below):
    When I use "setDefaultRenderer" I get the behaviour I expect. Fx. that number columns a right aligned, dates show as dates etc. However when I use "setCellRenderer" it eems that the functionality of the superclass is overridden ??. Any explanation - anyone ?
          TableColumnModel  tcModel;
          JTable table
          tcModel = table.getColumnModel();
          Enumeration       enum;
          enum = tcModel.getColumns();
          /* This works */     
          table.setDefaultRenderer(Object.class,new renderer()); //The renderer works for all objects.
          while ( enum.hasMoreElements() )
             tColumn = (TableColumn)enum.nextElement();
             /* But this does not !!? */
             /* tColumn.setCellRenderer(new renderer());   */
    class renderer extends DefaultTableCellRenderer
       public Component getTableCellRendererComponent(
          JTable _table,
          Object _value,
          boolean _isSelected,
          boolean _hasFocus,
          int _row, int _col)
       Component cell = super.getTableCellRendererComponent(_table,_value,_isSelected,_hasFocus,_row,_col);
       return cell ;
    }

    I have a class renderer as shown below.
    I would like to apply this renderer to my cells in my JTable (see below):
    When I use "setDefaultRenderer" I get the behaviour I expect. Fx. that number columns a right aligned, dates show as dates etc. However when I use "setCellRenderer" it eems that the functionality of the superclass is overridden ??. Any explanation - anyone ?
          TableColumnModel  tcModel;
          JTable table
          tcModel = table.getColumnModel();
          Enumeration       enum;
          enum = tcModel.getColumns();
          /* This works */     
          table.setDefaultRenderer(Object.class,new renderer()); //The renderer works for all objects.
          while ( enum.hasMoreElements() )
             tColumn = (TableColumn)enum.nextElement();
             /* But this does not !!? */
             /* tColumn.setCellRenderer(new renderer());   */
    class renderer extends DefaultTableCellRenderer
       public Component getTableCellRendererComponent(
          JTable _table,
          Object _value,
          boolean _isSelected,
          boolean _hasFocus,
          int _row, int _col)
       Component cell = super.getTableCellRendererComponent(_table,_value,_isSelected,_hasFocus,_row,_col);
       return cell ;
    }

  • Change the cell color in JTable?

    Hi all,
    I'm trying to do that, the user make a selection of multiple cells in a table. And when it press enter, I whant to change the color of the selected cells.(the isEditable of JTable it's already overwritten to return always false)
    I have already make my own CellRender, my problem is, because the cell remains unchanged the render are not called...
    Thanks,
    NeuralC

    You need not access this function when you want to paint a cell. This is how your code while instantiating the table should typically look like.
    JTable table = new JTable(model);
    table.setDefaultRenderer(Object.class,new MyCellRenderer());
    and
    public class MyTableCellRenderer extends JLabel implements TableCellRenderer
    public MyTableCellRenderer
    setOpaque(true);
    setBackground(Color.white);
    public Component getTable.....(JTable table,Object value,......) //fill all these things
    setFont(table.getFont());
    if(value != null && isSelected)
    setHorizontalAlignment(SwingConstants.RIGHT);
    setText(value);
    return this;
    When you set MyTableCellRenderer to the table, the getTableCellRedererComponent method is called automatically to renderer the cells and only the selected cells will be hightlighted in blue color. For a better understanding of how tables work and their corresponding Renderers work, you might have to read the tutorial on JTable. Do that as that would help you in removing all the confusion.
    Thanks,
    Kalyan

  • HELP!! set the cell color in jTable

    I need to set the color of a specific cell in jTable, but, I need to retain the old color in the jTable. It must not reset the whole table.
    would anyone help me in this problem... PLSSSSS its urgent

    A flexible variation on this is to specify formatting options in the JTable's client properties:
    // Use some sort of special "key" to indicate the cell and that you want to set the background color
    String key = "background:" + row + "," + column;
    table.putClientProperty(key, Color.green);You can then write a general table cell renderer that looks for these special formatting options and it doesn't disrupt your existing TableModel in any way:
    public class FormattingTableCellRenderer extends DefaultTableCellRenderer
      public Component getTableCellRendererComponent(JTable table, Object value, int row, int column, ...)
        Component component = super.getTableCellRendererComponent(table, value, row, column, ...);
        // See if the JTable specifies any properties to override the default format
        Color backgroundColor = (Color)table.getClientProperty("background:" + row + "," + column);
        if(backgroundColor != null)
          component.setBackground(backgroundColor);
        return component;
    }Any custom cell renderers you have then simply need to extend FormatTableCellRenderer instead of DefaultTableCellRenderer.
    It's very easy to add formatting options other than background, such as font, to the list of recognised attributes. You'll probably need to make some alterations to get it to recognise selection/focus but hopefully you get the idea.
    Hope this helps.

  • Enter a brief summary here holding the cell color in jtable

    Hai every body, I hope someone can rescue me. we r building a standalone application(trading system) for the StockMarket. we r trying to update the watchlist,which displays the market ticks.those who r in this domain can understand this as live streaming.Everything is fine.i could acheive this task.but now my boss has created a problem. he wants the jtable cell to hold the color,once the packet has appeared for that symbol.But currently my system(jtable) holds only the latest color.this can be explained further like this,accoring to the market movement,once the tick has come ,basing on the previous value,say if the value has increased i make the table cell as blue and if the value has decreased the table cell is made red. Now i'm really struggling to hold the colors of the previous ticks.can anyone suggest me a solution for this... i hope someone will come to my rescue... i customized the defaulttablecellrenderer.
    thanks in advance regards,
    RaviTeja

    I think having a custom renderer like this might address your issue.
    public Component getTableCellRendererComponent(JTable table,
         Object value, boolean isSelected, boolean hasFocus,
         int row, int col) {
         String oldString = getText();
         if(oldString == null || oldString.length() == 0) {
              oldString = "0.00";
         double oldValue = Double.parseDouble(oldString);
         double newValue = ((Double) value).doubleValue();
         if(oldValue < newValue) {
              //Set desired background and foreground colors.
         else if(oldValue > newValue) {
              //Set desired background and foreground colors.
         else {
              //Set desired background and foreground colors.
         setText(String.valueOf(newValue));
         return null;
    }Hope this helps..
    Sai Pullabhotla

  • Changing the cells atribute in JTable

    Can You help me change the first row background & font color and to bold font in my table - and a question if I use swing must I import awt libraties?
    I've read that if smbd use swing than he should stay away from awt in term not to mix these two technologies - how do You know that You are using a SWING or an AWT library?
    Thanks in advance, smartduck
    here is my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Inventory2_17 {
    public JPanel buildUI() {
    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createEmptyBorder(50, //zgoraj
    50, //levo
    50, //spodaj
    50) //desno
    Object[][] data = {{"Item Num","Item Name","Units","On hand"},
    {"B1242","Bolt","Each","1000"},{"N1242","Nut","Each","1200"},{"W1242","Washer","Each","1150"},{"N2323","Nails","Lbs","2250"}};
    Object[] stolpci = {"0","1","2","3"};
    JTable table = new JTable(data,stolpci);
    table.setRowHeight(30);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              for (int i=0;i<stolpci.length;i++)     {
                   table.getColumnModel().getColumn(i).setMinWidth(180);
              panel.add(table);
    return panel;
    public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Congratulations!! You are a good student.");
    Inventory2_17 app = new Inventory2_17();
    frame.getContentPane().add(app.buildUI(), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

    Just read the tutorial, would you? Everything you need to know is there, it is pointless to ask uninformed questions here before you read it.
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • Shading part of a JTable Cell dependent upon the value of the cell

    Hi
    Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
    What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
    The code for my renderer as it stands is:
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
         double percentageValue;
         double rectWidth;
         double rectHeight;
         JTable table;
         int row;
         int column;
         int x;
         int y;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (value instanceof Number)
                   this.table = table;
                   this.row = row;
                   this.column = column;
                   Number numValue = (Number)value;
                   percentageValue = numValue.doubleValue();
                   rectHeight = table.getRowHeight(row);
                   rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
              return this;
         public void paintComponent(Graphics g) {
            x = table.getCellRect(row, column, false).x;
            y = table.getCellRect(row, column, false).y;
              setOpaque(false);
            Graphics2D g2d = (Graphics2D)g;
            g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
            super.paintComponent(g);
    }and the following code produces a runnable example:
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class PercentageTestTable extends JFrame {
         public PercentageTestTable()
              Object[] columnNames = new Object[]{"A","B"};
              Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
              DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
              JTable test = new JTable(testModel);
              test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
              JScrollPane scroll = new JScrollPane();
              scroll.getViewport().add(test);
              add(scroll);
         public static void main(String[] args)
              PercentageTestTable testTable = new PercentageTestTable();
              testTable.pack();
              testTable.setVisible(true);
              testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }If anyone could help or point me in the right direction, I'd appreciate it.
    Ruanae

    This is an example I published some while ago -
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Fred120 extends JPanel
        static final Object[][] tableData =
            {1, new Double(10.0)},
            {2, new Double(20.0)},
            {3, new Double(50.0)},
            {4, new Double(10.0)},
            {5, new Double(95.0)},
            {6, new Double(60.0)},
        static final Object[] headers =
            "One",
            "Two",
        public Fred120() throws Exception
            super(new BorderLayout());
            final DefaultTableModel model = new DefaultTableModel(tableData, headers);
            final JTable table = new JTable(model);
            table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
            add(table);
            add(table.getTableHeader(), BorderLayout.NORTH);
        public class LocalCellRenderer extends DefaultTableCellRenderer
            private double v = 0.0;
            private double maxV;
            private final JPanel renderer = new JPanel(new GridLayout(1,0))
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.CYAN);
                    int w = (int)(getWidth() * v / maxV + 0.5);
                    int h = getHeight();
                    g.fillRect(0, 0, w, h);
                    g.drawRect(0, 0, w, h);
            private LocalCellRenderer(double maxV)
                this.maxV = maxV;
                renderer.add(this);
                renderer.setOpaque(true);
                renderer.setBackground(Color.YELLOW);
                renderer.setBorder(null);
                setOpaque(false);
                setHorizontalAlignment(JLabel.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                if (value instanceof Double)
                    v = ((Double)value).doubleValue();
                return renderer;
        public static void main(String[] args) throws Exception
            final JFrame frame = new JFrame("Fred120");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new Fred120());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • How can I change the coIor of one cell in a JTable

    Hello,
    I need to change the colours of the cells in a table. The problem is that when I try to change the colour of a one cell the colour of entire column is changed. See the way that I tried to use.
    TableCellRenderer cr = table.getCellRenderer(row, col);
    if (cr instanceof DefaultTableCellRenderer) {
        ((DefaultTableCellRenderer)cr).setBackground(bgColor);
    ......Please let me know if you have any suggestion
    Thanks a lot
    Jan

    try this ...
    In ur table call this
    ColorRenderer cell=new ColorRender();
    // for(int i=0;i<table.getModel().getColumnCount();i++){
    // TableColumn mod=this.getColumn((this.getModel().getColumnName(i)));
    mod.setCellRenderer(cell);
    And ur ColorRender calss should override DefaultTableCellRenderer like this
    class ColorRenderer extends DefaultTableCellRenderer {
    protected int align;
    public ColorRenderer(int align) {
    this.align=align;
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus, int row,
    int column) {
    setHorizontalAlignment(align);
    super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
    if(col==4){
    setBackground(Color.cyan);
    return this;

  • How do I change the colour of text in a cell in a JTable?

    I am trying to change the color of the text in a single cell in a JTable. I have tried not adding a cell renderer and it changes the colour of text in all cells.
    I have tried adding a cell renderer to the table and it does the same ie all cells text colour changes.
    I am able to add a cell renderer to a column and it changes all the cells in the column.
    I cannot figure out how to change just one single cell's text colour without effecting the other cells.

    Ok, so if i create my own cell renderer do I set it as the default renderer for the whole table i.e.
    table.setDefaultRenderer(MyCellRenderer, renderer);
    Does this set one cell renderer for the whole table or is there an individual one for each cell?

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • Unable to edit cells in JTable on single click of the cell.

    Hi,
    I am unable to edit a cell in JTable on single click of the cell. If I double click on the cell, I am able to edit it. Please help me.
    Thanks
    Subbu

    Thanks for all replies. Now, i am able to edit the cell on single click.

  • How can i add a MouseMotionlistener  to the cells in the JTable?

    hi !
    how can i add a MouseMotionlistener to the cells in the JTable?

    yes i have.but that is different from adding MouseMotionlistener to the cells for me .
    i just want get the values where the mouse moves to .

  • Return to the cell after data validation in JTable

    Hi,
    I am implementing an editable JTable. I want the focus or selection return to the current editing cell when the user inputing a wrong format data. I can catch the validation error and pop up a error message to user. But I can not return the focus or selection to the editing cell.
    If anyone has already solved this problem, please give me your solution.
    Thank you!
    I have tried:
    1.
    In tableChanged(TableModelEvent e) method:
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object data = newJTable.getValueAt(row, column);
    if(!validation(data)) // return true if validation OK
    editFailed = true;//class variable
    previousRow = row;//class variable
    previousCol = column;//class variable
    Add a focus listener to the table and implement the focus listener's focusLost method with:
    if(validationFailed)
    table.editCellAt(previousRow, previousCol);
    This does move the focus to the editing cells if you want to continue to edit the table.
    Problems are
    If you move the focus out of the table, the wrong date will be in the table or not edited.
    The selection color was shown on the next cell where you pointed your mouse to after you leave the editing cells.
    2. I have also tried to use:
    in the above focusLost method
    table.clearSelection();
    table.editCellAt(previousRow, previousCol);
    table.setRowSelectionInterval(previousRow, previousRow);
    table.setColumnSelectionInterval(previousCol, previousRow);
    But it did not change the selection.
    Shaolong

    This is the fix for the above problem.
    Basically we need to handle both mouse/keyboard actions on our own.
    This code returns the control to errorCell..
    /* TableCellValidator class */
    /* The class basically validates the input entry in a cell and */
    /* pops up a JOptionPane if its an invalid input */
    /* And an OK is clicked on the JOptionPane, the control returns back */
    /* to the same cell */
    /* Basic Idea: The controls Arrow/Tab/mouse clicks are handled by our */
    /* ----------- custom table. Its has been slightly tricky to handle */
    /* mouse clicks, since when you click the next cell, the */
    /* editingrow/editingcol advances. Hence the */
    /* previousrow/previouscol has been captured in the */
    /* setValueAt method. */
    /* To capture Table/Arrow/Numeric Arrow, The keyStrokes(TAB etc)*/
    /* assigned different AbstractionActions to execute like */
    /* validateBeforeTabbingToNextCell */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableCellValidator {
    * Constructor.
    * Basically instantiates the class and sets up the
    * JFrame object and the table.
    public TableCellValidator() {
    JFrame f = new JFrame("JTable test");
    f.getContentPane().add(new JScrollPane(createTable()), "Center");
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    * A method which created our custom table.
    * The JTable methods processMouseEvent
    * and setValueAt are overridden to handle
    * Mouseclicks.
    * The Tables ActionMap is fed with different
    * AbstractAction classes eg: (validateBeforeTabbingToNextCell)
    * (Scroll down below for the innerclass
    * validateBeforeTabbingToNextCell).
    * So basically when TAB is pressed the stuff present
    * in the validateBeforeTabbingToNextCell's actionPerformed(..)
    * method is performed.
    * So we need to handle all the stuff a TAB does.
    * ie. if a TAB hits the end of the row, we need to increment
    * it to the next Row (if the validation is successful)
    * in the current row etc..
    * @return JTable
    * @see validateBeforeTabbingToNextCell
    * @see validateBeforeShiftTabbingToNextCell
    * @see validateBeforeMovingToNextCell
    * @see validateBeforeMovingDownToCell
    * @see validateBeforeMovingUpToCell
    * @see validateBeforeMovingLeftToCell
    private JTable createTable() {
    JTable table = new JTable(createModel()){
    private int previousRow =0;
    private int previousCol =0;
    * Processes mouse events occurring on this component by
    * dispatching them to any registered
    * <code>MouseListener</code> objects.
    * <p>
    * This method is not called unless mouse events are
    * enabled for this component. Mouse events are enabled
    * when one of the following occurs:
    * <p><ul>
    * <li>A <code>MouseListener</code> object is registered
    * via <code>addMouseListener</code>.
    * </ul>
    * <p>Note that if the event parameter is <code>null</code>
    * the behavior is unspecified and may result in an
    * exception.
    * @param e the mouse event
    * @see java.awt.event.MouseEvent
    * @see java.awt.event.MouseListener
    * @see #addMouseListener
    * @see #enableEvents
    * @since JDK1.1
    protected void processMouseEvent(MouseEvent e) {
    boolean canMoveFocus = true;
    int currentRowAndColumn[] = getCurrentRowAndColumn(this); //we pull the current row and column
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    if ( e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_CLICKED) {
    stopCurrentCellBeingEdited(this); //stop the cellbeing edited to grab its value
    final String value = (String)getModel().getValueAt(row,column);
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    JOptionPane.showMessageDialog(null,"Alpha value ="+ value ,"Invalid entry!",JOptionPane.WARNING_MESSAGE);
    changeSelection(previousRow,previousCol, true, true);
    editCellAt(previousRow, previousCol);
    requestFocus(); // or t.getEditorCompo
    if ( canMoveFocus ) {
    super.processMouseEvent(e);
    * The method setValueAt of the JTable is overridden
    * to save the previousRow/previousCol to enable us to
    * get back to the error cell when a Mouse is clicked.
    * This is circumvent the problem, when a mouse is clicked in
    * a different cell, the control goes to that cell and
    * when you ask for getEditingRow , it returns the row that
    * the current mouse click occurred. But we need a way
    * to stop at the previous cell(ie. the cell that we were editing
    * before the mouse click occurred) when an invalid data has
    * been entered and return the focus to that cell
    * @param aValue
    * @param row
    * @param col
    public void setValueAt(Object aValue,int row, int col) {     
    this.previousRow = row;
    this.previousCol = col;
    super.setValueAt(aValue,row,col);
    /* These are the various KeyStrokes like
    ENTER,SHIFT-TAB,TAB,Arrow Keys,Numeric Arrow keys being assigned an Abstract action (key string ) in to the
    inputMap first . Then an Action is assigned in the ActionMap object
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0) ,"validateBeforeTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1) ,"validateBeforeShiftTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getActionMap().put("validateBeforeTabbingToNextCell",
    new validateBeforeTabbingToNextCell());
    table.getActionMap().put("validateBeforeShiftTabbingToNextCell",
    new validateBeforeShiftTabbingToNextCell());
    table.getActionMap().put("validateBeforeMovingToNextCell",
    new validateBeforeMovingToNextCell());
    table.getActionMap().put("validateBeforeMovingDownToCell",
    new validateBeforeMovingDownToCell());
    table.getActionMap().put("validateBeforeMovingUpToCell",
    new validateBeforeMovingUpToCell());
    table.getActionMap().put("validateBeforeMovingLeftToCell",
    new validateBeforeMovingLeftToCell());
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    return table;
    * A table model is created here for 5 rows/5 columns.
    * And the isCellEditable is overridden to return true,
    * indicating that the cell can be edited.
    * So fine tuned control can be done here by saying,
    * the user can be allowed to edit Row 1,3 or 5 only.
    * or column 1 only etc..
    * @return DefaultTableModel
    private DefaultTableModel createModel() {
    DefaultTableModel model = new DefaultTableModel(5, 5) {
    public boolean isCellEditable(int row, int column) {
    return true;
    return model;
    * This method basically returns the currentRow/currentCol value
    * If the current Row/Col is being edited then
    * it returns the getEditingRow/getEditingColumn
    * If its not being edited,
    * it return the getAnchorSelectionIndex of the JTables
    * ListSelectionModel.
    * If the column or row is -1, then it return 0.
    * The first element in the int[] array is the row
    * The second element in the int[] array is the column
    * @param t input a JTable
    * @return int[]
    * @see ListSelectionModel
    * @see JTable
    private int[] getCurrentRowAndColumn(JTable t){
    int[] currentRowAndColum = new int[2];
    int row, column;
    if (t.isEditing()) {
    row = t.getEditingRow();
    column = t.getEditingColumn();
    } else {
    row = t.getSelectionModel().getAnchorSelectionIndex();
    if (row == -1) {
    if (t.getRowCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column =t.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
    if (column == -1) {
    if (t.getColumnCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column = 0;
    currentRowAndColum[0]=row;
    currentRowAndColum[1]=column;
    return currentRowAndColum;
    * Tbis basically a wrapper method for CellEditors,
    * stopCellEditing method.
    * We need to do this because,
    * for instance we have entered a value in Cell[0,0] as 3
    * and when we press TAB or mouse click or any other relevant
    * navigation keys,
    * ** IF the cell is BEING EDITED,
    * when we do a getValueAt(cellrow,cellcol) at the TableModel
    * level , it would return "null". To overcome this problem,
    * we tell the cellEditor to stop what its doing. and then
    * when you do a getValueAt[cellrow,cellcol] it would
    * return us the current cells value
    * @param t Input a JTable
    * @see CellEditor
    private void stopCurrentCellBeingEdited(JTable t){
    CellEditor ce = t.getCellEditor(); /*this not the ideal way to do..
    since there is no way the CellEditor could be null.
    But a nullpointer arises when trying to work with mouse.. rather than just
    keyboard" */
    if (ce!=null) {
    ce.stopCellEditing();
    * The following Action class handles when a
    * RIGHT ARROW or NUMERIC RIGHT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * next Cell.. else take it back to the currentCell
    class validateBeforeMovingToNextCell extends AbstractAction {
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There is just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to
    * down by one Cell.. else take it back to the currentCell
    * @param e
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    if (column >= t.getColumnCount())
    column = column-1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * down by Cell.. else take it back to the currentCell
    class validateBeforeMovingDownToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row++;
    if (row >= t.getRowCount())
    row = row - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * UP ARROW or NUMERIC UP ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingUpToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row--;
    if (row <0)
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * LEFT ARROW or NUMERIC LEFT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingLeftToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    if (column <0)
    column = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while (row < rows) {
    while (column < columns) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column++;
    row++;
    column = 0;
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a SHIFT TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeShiftTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while ((row < rows) && (row >= 0)) {
    while ((column < columns) && (column >= 0)) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column--;
    row--;
    column = columns - 1;
    row = rows - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    public static void main(String[] args) {
    new TableCellValidator();

  • JButton inside the cell of JTable

    JButton buttonInCellOfTable = new JButton();
    buttonInCellOfTable.setBackground(Color.RED);
    buttonInCellOfTable.setText("MORE");
    buttonInCellOfTable.setPreferredSize(new Dimension(10, 22));
    buttonInCellOfTable.setMinimumSize(new Dimension(10, 22));
    buttonInCellOfTable.setMaximumSize(new Dimension(10, 22));
    myJTable.addRow("No. 1", buttonInCellOfTable);
    But Color and size isn't shown unlike those are set.
    What can I do?

    * @(#)ButtonTableCellRenderer.java     Tiger     2005 April 29
    package com.yahoo.ron.table;
    import java.awt.Component;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax,swing.JTable;
    import javax.swing.table.TableCellRenderer;
    * @author     Ronillo Ang - [email protected]
    final public class ButtonTableCellRenderer extends JButton implements TableCellRenderer{
         public ButtonTableCellEditor(ActionListener actionListener){
              super("Editor");
              if(actionListener == null)
                   throw new NullPointerException();
              addActionListener(actionListener);
         public Component getTableCellRenderComponent(JTable table, Object value, boolean selected, boolean hasFocus, int row, int col){
              if(value instanceof String){
                   String text = String.valueOf(value);
                   setText(text);
              else
                   setText("Unknown value");
              return this;
    * @(#)TestingButtonTableCellRenderer.java      Tiger     2005 April 29
    package com.yahoo.ron.test;
    import com.yahoo.ron.table.ButtonTableCellRenderer;
    import com.yahoo.ron.table.UneditableTableModel;
    import com.yahoo.ron.ThreadMonitor;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    * @author     Ronillo Ang - [email protected]
    * A class to test com.yahoo.ron.table.ButtonTableCellRenderer
    public class TestingButtonTableCellRenderer implements ActionListener{
         public TestingButtonTableCellRenderer(){
              JFrame frame = new JFrame("Testing ButtonTableCellRenderer");
              frame.getContentPane().setLayout(new GridLayout(1, 1));
              JTable table = new JTable(new UneditableTableModel(new ThreadMonitor()));
              TableColumnModel tableColumnModel = table.getColumnModel();
              // get the last column.
              TableColumn tableColumn = tableColumnModel.getColumn(tableColumnModel.getColumnCount() - 1);
              // apply the cell renderer.
              tableColumn.setCellRenderer(new ButtonTableCellRenderer(this));
              frame.getContentPane().add(new JScrollPane(table));
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         public void actionPerformed(ActionEvent ae){
              // do nothing for now.
         static public void main(String[] args){
              new TestingButtonTableCellRenderer();
    // Okie!! I dont include my source of ThreadMonitor.java and UneditableTableModel.
    // If problem occur, make some modification. Okie!
    // Thanks! God bless you all!

Maybe you are looking for

  • I am trying to download itunes and keep getting an error message cannot access network location %appdata%

    I am trying to download itunes to windows 7 and keep getting the error message "cannot access network location $APPDATA%\." I have contacted an Apple advisor and was not able to resolve the problem. What to do?

  • Running Vista on Macbook Pro

    Hello, Purchased a MacBook Pro 2 weeks ago. 2.5Ghz, 4Gb ram, 15". For a piece of software called DSLR Remote I need to upgrade from Windows XP to Vista. I ran the Vista upgrade advisor and it told me that Vista would not work with the NVDIA GeForce 8

  • Problems with Mini--continued reboot after update

    I recently was given a Mini to play with. I was having some issues with it when I first received it. I read some forum posts and some other non-apple related help files on the internet. I finally got the Mini to work correctly, at least I was able to

  • Help me please SB0

    I buy mini pc name Egear inside have Creative Sound Card Model SB0040 i am not sure real namemodel but i have ploblem i want ot know pin out of this sound because this card is not usuallynot have pin in AUD_EXT Thank you to help me ***Picture link ht

  • 1.5.1/1.5/EA3/EA2/EA1: Another deadlock

    Hi, I was running a single query with bind variables by pushing the Run Query button, changing values between executions. Until sqldev locked up on pushing the button. Here's the stack dump: Full thread dump Java HotSpot(TM) Client VM (10.0-b19 mixed