JTable Usage !!

Hi ,
Can I insert a new column in an existed tabel ? How to hide the grid of a tabel ? For a special column , I want it just can access date format , how to do this? Thanks.
Liwei

You need to create a custom TableModel and give it methods to allow you to add (and indeed remove) columns. The TableModel interface has two methods
int getColumnCount()
int getRowCount()
Since your constructing your own TableModel (probably overriding AbstractTableModel), you'll have to override these two methods so that you can supply the correct current number of columns and rows.
Here's an example:
import javax.swing.table.*;
public class DynamicTableModel extends AbstractTableModel {
     private String[] columnNames;
     /** Create the dynaic table model with a list of column names*/
     public DynamicTableModel(String[] columnnames) {
          columnNames=columnnames;
     //Add a new column with a given title
     public void addNewColumn(String newColName) {
          //'Extend' the column names array and add new name to the end
          String[] newColumns = new String[columnNames.length+1];
          for (int i=0;i<columnNames.length;i++) {
               newColumns=columnNames[i];
          newColumns[columnNames.length]=newColName;
          columnNames=newColumns;
     /** Returns the contents of a cell, in this case a string*/
     public Object getValueAt(int rowIndex,int columnIndex) {
          String res=columnNames[columnIndex]+" "+Integer.toString(rowIndex);
          return res;
     /** Gets the name of the specified column*/
     public String getColumnName(int columnIndex) {
          return columnNames[columnIndex];
     /** Tells the table how many columns are in this tablemodel*/
     public int getColumnCount() {
          return columnNames.length;
     /** Normally, you'd have something in a model's code to hold the data, but here
     I'm just use fixed data to demo the whole concept*/
     public int getRowCount() {
          return 5;
To hide the grid lines, use JTable.setGridColor(Color gridColor) to the background color of the cells (say, Color.WHITE).

Similar Messages

  • Jtable memory usage

    I have a legend that i use in my product that contains 2 color menu butons and some text. It used to be a graphic with all this stuff just painted on top of it and the two color menu buttons placed on top. I have converted it to a jtable with the color buttons and text loacated in the cells of the table. when i run a test on the old legend compared to the new legend, i get a memmory increase from 39 Mb to 52 Mb. I am just wondering if this is due to JTables using a lot more memory than my previouse implementation, or if this is some other underying problem. If any one could give me any insight into this issue I would really appreciate it. Thank you

    just thought I'd bump this up once to see if I might get an answer.

  • L&F mapping JTable

    The look and feel values chosen for the JTable under windows do not feel right to me (albeit that I cannot find many examples of tables under windows).
    I am trying to provide some workarounds that follow what most people expect to happen but am a little unclear on what should happen on some key presses for the JTable in windows look and feel
    Space handling
    From one of the MS windows books it suggests that the space key is a selection key, thus when you press space a row in a table should be selected (and when you press again it should deselect the row?)
    The JList has functionality for the space key
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.
    Enter handling
    The enter key press is supposed to activate the default button
    or commit a text field under edit.
    F2 puts a field under edit
    q2) Should the enter key put an editable cell under edit (same mouse action as single or double click to edit)?
    q3) if not should the first enter key stop cell editing and a second press activate the default button, with only a single enter to activate default button if a cell is not under edit
    Escape handling
    The escape key will cancel editing of a cell that is under edit.
    q4) should the event not be passed on when editing has been cancelled so that dialogs with a canel button can be dismissed
    or
    q5) should the first escape cancel editing while the second escape will action the escape action of the window.
    Any links to "highly regarded" useability/look and feel sites would be helpful - sun does not appear to provide much on this subject
    I've read both their l&f and advanced l&f books and they just scratch the surface of look and feel without much realworld appliance to real gui issues.
    Might be useful to others: Some of the code that I was trying to create goes like....
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyEvent;
    import java.math.BigDecimal;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.CellEditor;
    import javax.swing.InputMap;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.KeyStroke;
    import javax.swing.ListSelectionModel;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.LineBorder;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    /** Provides utility methods for the JTable and JCSortableTable classes
    * @author  */
    public final class JTableUtil
          * Constructor for JCTableUtil.
         private JTableUtil()
              super();
         /** will resize the last column of a table to fill the gap
          * if the width of the columns is narrower than the width of the
          * table
          * @param table to act upon
         static void resizeLastColumn(final JTable table)
              TableColumn lastColumn = getLastVisibleColumn(table);
              if (lastColumn != null)
                   int gap = getLastColumnGap(table);
                   if (gap > 0)
                        int newLastColumnWidth = gap + lastColumn.getWidth();
                        lastColumn.setWidth(newLastColumnWidth);
                        lastColumn.setPreferredWidth(newLastColumnWidth);
                        redrawTable(table);
          * Determines if there is a gap between the last column in a table
          * and the border of the table.
          * Works if the table is drawn on the page or is in the
          * viewport of a scroll pane.
          * @param table to act upon
          * @return the gap in pixels between last column and table edge.
         static int getLastColumnGap(final JTable table)
              int widthTable = getTableWidth(table);
              int lastVisColIndex = getLastVisibleColumnIndex(table);
              TableColumnModel columnModel = table.getColumnModel();
              int widthColumns = columnModel.getTotalColumnWidth();
              final TableColumn lastColumn = columnModel.getColumn(lastVisColIndex);
              // gap is number of pixels from right hand edge of last column
              // to right hand edge of the table
              int gap = widthTable - widthColumns;
              return gap;
          * Determines the width of a table returning the table width if
          * table is painted onto a panel, but if the table is painted
          * into a scroll pane then it is the scroll pane viewport width that is returned
          * This is to capture that the width of the table may be less than the
          * width of the viewport - ie if there is a gap after the last column in a table.
          * @param table to act upon
          * @return the width of the table in pixels
         static int getTableWidth(final JTable table)
              int widthTable = table.getWidth();
              Object tableParent = table.getParent();
              JViewport tableViewPort = null;
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   widthTable = tableViewPort.getWidth();
              return widthTable;
         /** Cause the table to redraw wether table is painted on a panel
          * or in a scroll pane
          * @param table to act upon
         static void redrawTable(final JTable table)
              Component tableRegion = table;
              Component tableParent = table.getParent();
              if (tableParent instanceof JViewport)
                   tableRegion = tableParent;
              tableRegion.invalidate();
              tableRegion.validate();
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return index (0 based) of the last visible column.
         static int getLastVisibleColumnIndex(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              boolean found = false;
              int columnIndex = columnModel.getColumnCount();
              while (!found && columnIndex > 0)
                   columnIndex--;
                   if (columnModel.getColumn(columnIndex).getWidth() != 0)
                        found = true;
              return columnIndex;
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return TableColumn - the last visible column.
         static TableColumn getLastVisibleColumn(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              return columnModel.getColumn(getLastVisibleColumnIndex(table));
          * Add the currency symbol to a JCTable/JCListTable column header
          * e.g. 'Salary' becomes 'Salary (�)'
         public static void addCurrencySymbol(JTable table, Object columnKey)
              //@todo - update to work with JTable
              TableColumnModel columnModel = table.getTableHeader().getColumnModel();
              int columnIndex = columnModel.getColumnIndex(columnKey);
              TableColumn column = columnModel.getColumn(columnIndex);
              Object object = column.getHeaderValue();
              if (object instanceof JLabel)
                   JLabel columnLabel = (JLabel) object;
                   SlacCurrency.getInstance().addCurrencySymbol(columnLabel);
              else
                   // @todo log here ???
              // is above correct - need to get the JLabel rendered from the table
              // in the scroll pane?          
         /** Provides a sum of a column of BigDecimals
          * @param tableModel model containing column that you wish to sum
          * @param column the column that you wish to be summed, must contain numeric values and not strings
         public static BigDecimal calculateTotalForColumn(final TableModel tableModel, final int column)
              int numRows = tableModel.getRowCount();
              BigDecimal total = new BigDecimal("0");
              for (int row = 0; row < numRows; row++)
                   Object value = tableModel.getValueAt(row, column);
                   if (value instanceof BigDecimal)
                        BigDecimal decimalValue = (BigDecimal) value;
                        total = total.add(decimalValue);
                   else
                        //Logger.logGeneralFailure("", ErrorCodes.GUI_ERROR, this);
              return total;
          * Provides the swing setting JTable.AUTO_RESIZE_OFF.
          * <p>
          * In this situation if the width of the columns is smaller than the width
          * of the table then there will be a gap after the last column.
          * <p>
          * This method will add a ComponentListener to the table and or
          * scroll pane viewport so that there is no gap after the last column.
          * @param table to act upon
         public static void configureAutoResizeOff(final JTable table)
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              Component tableParent = table.getParent();
              JViewport tableViewPort = null;
              ComponentAdapter gapFiller = new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                        super.componentResized(e);
                        JTableUtil.resizeLastColumn(table);
              table.addComponentListener(gapFiller);
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   tableViewPort.addComponentListener(gapFiller);
         /** Method provides fixes to provide standard handling for keyboard and mouse usage
          * <ul>
          *    <li> spacebar - selection handling of rows that have focus emphasis see fixSpacebarHandling()
          *    <li> initial focus handling - table should give visual feedback when gaining focus
          *    <li>
          * </ul>
          * @param table - the table to add standards handling to
         public static void setupKeyboardMouseHandling(JTable table)
              fixTableGainsFocusOnFirstEntry(table);
              fixSpacebarHandling(table);
              fixCtrlSpacebarHandling(table);
              fixShiftSpacebarHandling(table);
              fixCtrlUpDownHandling(table);
              fixFocusHighlight();
              fixEscEnter(table);
         /** Add fixes to the look and feel handling for a JTable
          * Enter on a table will do different things depending on the mode of the table
          * <p>
          * if a cell is being edited then
          * Enter will do what normally happens to a field under edit - ie stop the editing and commit
          * Escape will cancel the editing
          * <p>
          * if a cell is not under edit then
          * Enter will activate the default button
          * Escape will activate the default cancel button (see FrameUtil.addEscapeKeyAction())
         static void fixEscEnter(final JTable table)
              final RootPaneContainer root = (RootPaneContainer)SwingUtilities.windowForComponent(table);
              final String escapeKey = "escapeAction";
              Action escapeAction = new AbstractAction(escapeKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.cancelCellEditing();
                        else
                             Window parentWindow = SwingUtilities.windowForComponent(table);
                             Action windowEscapeAction = FrameUtil.getEscapeKeyAction(root);
                             windowEscapeAction.actionPerformed(actionEvent);
              final String enterKey = "enterAction";
              Action enterAction = new AbstractAction(enterKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.stopCellEditing();
                        else
                             root.getRootPane().getDefaultButton().doClick();
              InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              table.getActionMap().put(escapeKey, escapeAction);
              table.getActionMap().put(enterKey, enterAction);
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escapeKey);          
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enterKey);          
         static void fixFocusHighlight()
              Border focusCellHighlightBorder = new DashedLineBorder(Color.BLACK);
              UIManager.put("Table.focusCellHighlightBorder", focusCellHighlightBorder);
         /** If you do not setup a table to have a row selected then there is a bug where for example
          * you use an accelerator key to put focus in the table and you get no visual feedback that
          * the table has focus - ie no focus emphasis - dashed box
          * @param table - the table to fix
         static void fixTableGainsFocusOnFirstEntry(JTable table)
              // for first time tabbing to table make sure that first cell has focus
              // don't seem to need this fix under windows XP
              table.getSelectionModel().removeSelectionInterval(0, 0);
         /** fix spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * spacebar - select the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixSpacebarHandling(JTable table)
              KeyStroke ksSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
              final String ACTION_SPACE = "SPACE";
              Action spaceAction = new AbstractAction(ACTION_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksSpace, ACTION_SPACE);
              table.getActionMap().put(ACTION_SPACE, spaceAction);
         /** fix ctrl + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * ctrl + spacebar - toggle selection on the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlSpacebarHandling(JTable table)
              KeyStroke ksCtrlSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.CTRL_MASK, true);
              final String ACTION_CTRL_SPACE = "CTRLSPACE";
              Action ctrlSpaceAction = new AbstractAction(ACTION_CTRL_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        boolean isCurrentRowSelected = selectModel.isSelectedIndex(currentRowIndex);
                        if (isCurrentRowSelected)
                             selectModel.removeSelectionInterval(currentRowIndex, currentRowIndex);
                        else
                             selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksCtrlSpace, ACTION_CTRL_SPACE);
              table.getActionMap().put(ACTION_CTRL_SPACE, ctrlSpaceAction);
         /** fix shift + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * shift + spacebar - extend the selection from the anchor to the lead index.
          * this might still be a bit funny in java 1.4.2 and code may need to be changed slightly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixShiftSpacebarHandling(JTable table)
              KeyStroke ksShiftSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.SHIFT_MASK, true);
              final String ACTION_SHIFT_SPACE = "SHIFTSPACE";
              Action shiftSpaceAction = new AbstractAction(ACTION_SHIFT_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        int startRowIndex = selectModel.getLeadSelectionIndex();
                        selectModel.setSelectionInterval(startRowIndex, currentRowIndex);
              table.getInputMap().put(ksShiftSpace, ACTION_SHIFT_SPACE);
              table.getActionMap().put(ACTION_SHIFT_SPACE, shiftSpaceAction);
         /** fix ctrl + down or up handling - move focus emphasis up or down accordingly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlUpDownHandling(JTable table)
              final String ACTION_UP = "CTRLUP";
              KeyStroke ksCtrlUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.CTRL_MASK, true);
              KeyStroke ksCtrlDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.CTRL_MASK, true);
              Action ctrlUpAction = new CtrlUpDownAction(ACTION_UP, true);
              final String ACTION_DOWN = "CTRLDOWN";
              Action ctrlDownAction = new CtrlUpDownAction(ACTION_DOWN, false);
              table.getInputMap().put(ksCtrlUp, ACTION_UP);
              table.getActionMap().put(ACTION_UP, ctrlUpAction);
              table.getInputMap().put(ksCtrlDown, ACTION_DOWN);
              table.getActionMap().put(ACTION_DOWN, ctrlDownAction);
    * Action for moving focus emphasis up or down
    class CtrlUpDownAction extends AbstractAction
         private boolean m_isUp = true;
         /** Ctor controlling direction of focus emphasis
          * @param name of the action
          * @param isUp - true if dirction of action is up, else false
         public CtrlUpDownAction(String name, boolean isUp)
              super(name);
              m_isUp = isUp;
         /** Moves the focus emphasis
          * @param actionEvent - see javax.swing.AbstractAction class for details
         public void actionPerformed(ActionEvent actionEvent)
              JTable table = (JTable) actionEvent.getSource();
              ListSelectionModel selectModel = table.getSelectionModel();
              int nextRowIndex =
                   getNextRowIndex(table.getRowCount(), selectModel.getAnchorSelectionIndex());
              if (selectModel.isSelectedIndex(nextRowIndex))
                   selectModel.addSelectionInterval(nextRowIndex, nextRowIndex);
              else
                   selectModel.removeSelectionInterval(nextRowIndex, nextRowIndex);
         /** Gets the index of the next row depending on direction up or down
          * @param rowCount - number of rows in the table
          * @param currentRowIndex - index of the row that has focus emphasis
          * @return the index of the next row
         private int getNextRowIndex(int rowCount, int currentRowIndex)
              int nextRowIndex = -1;
              if (m_isUp && currentRowIndex > 0)
                   // emphasis moving up one row
                   nextRowIndex = currentRowIndex - 1;
              else if (!m_isUp && currentRowIndex < (rowCount - 1))
                   // emphasis moving down one row
                   nextRowIndex = currentRowIndex + 1;
              return nextRowIndex;
    /** Draws a dashed line (well more of a dotted line)
    * Used for eg drawing focus emphasis rectangle
    * Class draws a rectangle of chosen colour overlaid with a dashed white line.
    class DashedLineBorder extends LineBorder
         private BasicStroke m_lineStroke = new BasicStroke();
         private BasicStroke m_dashStroke =
              new BasicStroke(
                   m_lineStroke.getLineWidth(),
                   BasicStroke.CAP_BUTT,//m_lineStroke.getEndCap(),
                   m_lineStroke.getLineJoin(),
                   m_lineStroke.getMiterLimit(),
                   new float[] { 1,1,1 },
                   0);
          * Constructor for DashedLineBorder.
          * @param color
         public DashedLineBorder(Color color)
              super(color);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
         public DashedLineBorder(Color color, int thickness)
              super(color, thickness);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
          * @param roundedCorners
         public DashedLineBorder(Color color, int thickness, boolean roundedCorners)
              super(color, thickness, roundedCorners);
         /** Similar to LineBorder's method but draws a line in the chosen colour
          * before drawing a white dashed line on top of it
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
              Color oldColor = g.getColor();
              int i;
              Graphics2D g2 = (Graphics2D) g;
              g2.setStroke(m_lineStroke);
              g.setColor(lineColor);
              drawRect(g, x, y, width, height);
              g2.setStroke(m_dashStroke);
              g.setColor(Color.WHITE);
              drawRect(g, x, y, width, height);
              g.setColor(oldColor);
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         private void drawRect(Graphics g, int x, int y, int width, int height)
              // extracted from Java LineBorder.paintBorder
              int i;
              /// PENDING(klobad) How/should do we support Roundtangles?
              for (i = 0; i < thickness; i++)
                   if (!roundedCorners)
                        g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1);
                   else
                        g.drawRoundRect(
                             x + i,
                             y + i,
                             width - i - i - 1,
                             height - i - i - 1,
                             thickness,
                             thickness);
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.image.ImageProducer;
    import java.io.IOException;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
    import javax.swing.RootPaneContainer;
    * Provides static utility methods for JFrames.
    public final class FrameUtil {
        * No instances allowed. Just use the static methods.
       private FrameUtil() {
          super();
        * Sets the button that is "activated" when the escape key is used.
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key button should be set.
        * @param button The button which should be clicked automatically when the escape key is pressed.
       public static void setEscapeKeyButton(final RootPaneContainer jFrame, final JButton button) {
          addEscapeKeyAction(jFrame, new AbstractAction() {
             public void actionPerformed(final ActionEvent evt) {
                button.doClick();
        * Adds an action to the jframe's  action map that is triggered by the Escape key.
        * (If you just want to simulate a button click when the escape key is pressed then
        * use setEscapeKeyButton.)
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
        * @param action The action that is executred when the escape key us pressed,
       public static void addEscapeKeyAction(final RootPaneContainer jFrame, final Action action) {
          String actionKey = "escapeAction";
          KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          // using getRootPane rather than getContentPane, content pane doesn't work in all
          // scenarios
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          inputMap.put(escape, actionKey);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          actionMap.put(actionKey, action);
        * Finds the escape action for the given frame or dialog if one was added
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
       public static Action getEscapeKeyAction(final RootPaneContainer jFrame)
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          Object actionKey = inputMap.get(escapeKeyStroke);
          Action escapeAction = null;
          if(actionKey != null)
             escapeAction = actionMap.get(actionKey);
          return escapeAction;

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • JTable/jlist with word wrapping cells?

    Hello all,
    I got a simple looking problem but i can't seem to find any working solution for it:
    A jtable or jlist with cells that wordwrap text (cells differ in height).
    I found many examples on groups.google and this forum but they all seem to suffer a 100% processor load when 2 or more cells differ in height.
    Can anyone point me to a working example?
    Kind regards,
    Twan

    Thanks! That's a real live saver.
    I had been looking for a solution for several days, strange google did not yet found the mentioned page, cause it contains usefull information.
    I've just implemented the multiline table and it works without any problems and most important without 100% cpu usage.
    The bucks are comming your way ;-)

  • JTable in Form

    Dear friends
    I searched how can I make a gride (like excel gride) in oracle form and I'll have the followin control : sort on column , resize column and move column between eachother, then I read I must use JTable with Bean Area in oracle form( I'm not sure is it correct or not), But I couldn't find how I can do it.
    If I can do it with JTable and Bean Area please tell me step by step the method.
    Thanks alot

    I don't know how to run java console, but on the form I get When New Record Instance from the beginning of form running.Nothing else.
    Where is the Java console? How can I run it?
    When I run the form and try to open sun java console from internet explorer, explorer closes.
    While form is running before update I opened java.exe, it closes also.
    Java Console things
    Oracle JInitiator: Version 1.3.1.22
    Using JRE version 1.3.1.22-internal Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\JALEO
    User has overriden browser's proxy settings.
    Proxy Configuration: no proxy
    JAR cache enabled
    Location: C:\Documents and Settings\JALEO\Oracle Jar Cache
    Maximum size: 50 MB
    Compression level: 0
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    q: hide console
    s: dump system properties
    t: dump thread list
    x: clear classloader cache
    0-5: set trace level to <n>
    Loading http://jaleo.sarar.com.tr:8890/forms/java/frmall_jinit.jar from JAR cache
    java.io.FileNotFoundException: File not found: http://jaleo.sarar.com.tr:8890/forms/java/icons.jar
         at sun.plugin.protocol.jdk12.http.HttpURLConnection.getInputStream(Unknown Source)
         at oracle.jre.protocol.jar.HttpUtils.followRedirects(Unknown Source)
         at oracle.jre.protocol.jar.JarCache$CachedJarLoader.download(Unknown Source)
         at oracle.jre.protocol.jar.JarCache$CachedJarLoader.load(Unknown Source)
         at oracle.jre.protocol.jar.JarCache.get(Unknown Source)
         at oracle.jre.protocol.jar.CachedJarURLConnection.connect(Unknown Source)
         at oracle.jre.protocol.jar.CachedJarURLConnection.getJarFile(Unknown Source)
         at sun.misc.URLClassPath$JarLoader.getJarFile(Unknown Source)
         at sun.misc.URLClassPath$JarLoader.<init>(Unknown Source)
         at sun.misc.URLClassPath$2.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.misc.URLClassPath.getLoader(Unknown Source)
         at sun.misc.URLClassPath.getLoader(Unknown Source)
         at sun.misc.URLClassPath.getResource(Unknown Source)
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClassInternal(Unknown Source)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at oracle.ewt.util.FocusUtils.<clinit>(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.<clinit>(Unknown Source)
         at oracle.ewt.laf.oracle.OracleLookAndFeel._initCommonFixedDefaults(Unknown Source)
         at oracle.ewt.laf.oracle.OracleLookAndFeel._getCommonDefaults(Unknown Source)
         at oracle.ewt.laf.oracle.OracleLookAndFeel._getIndexedDefaults(Unknown Source)
         at oracle.ewt.laf.oracle.OracleLookAndFeel.getDefaults(Unknown Source)
         at oracle.ewt.lwAWT.BufferedApplet.getUIDefaults(Unknown Source)
         at oracle.ewt.lwAWT.BufferedApplet.<init>(Unknown Source)
         at oracle.ewt.swing.JBufferedApplet.<init>(Unknown Source)
         at oracle.forms.engine.Main.<init>(Unknown Source)
         at java.lang.Class.newInstance0(Native Method)
         at java.lang.Class.newInstance(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    WARNING: Unable to cache http://jaleo.sarar.com.tr:8890/forms/java/icons.jar
    Loading http://jaleo.sarar.com.tr:8890/forms/java/frmwebutil.jar from JAR cache
    Loading http://jaleo.sarar.com.tr:8890/forms/java/jacob.jar from JAR cache
    Loading http://jaleo.sarar.com.tr:8890/forms/java/fjtable.jar from JAR cache
    proxyHost=null
    proxyPort=0
    connectMode=HTTP, native.
    Forms Applet version is : 10.1.2.0
    SET_DECIMAL_SEPARATORS:.,
    SET_DATE_FORMAT:dd/MM/yyyy
    SET_NUM_FORMAT:#0.00
    SET_INT_FORMAT:##########
    SET_IMAGE_SIZE:200,-1
    INIT:false
    *** raz ***
    SETSEPARATOR:^
    SETARRAYSIZE:4,5
    ArraySize : 4 columns 5 rows
    SETHEADER:ROWID^^DEPTNO^^DNAME^^LOC
    SET_COLS_TYPE:CHAR^INTEGER^CHAR^CHAR
    SETDATA:AAAMjTAAEAAAAEEAAA^10^ACCOUNTING^lDAHO
    SETDATA:AAAMjTAAEAAAAEEAAB^20^RESEARCH^DALLAS
    SETDATA:AAAMjTAAEAAAAEEAAC^30^SALES^CHICAGO
    SETDATA:AAAMjTAAEAAAAEEAAD^40^OPERATIONS^BOSTON
    SETDATA:AAAMjTAAEAAAAEHAAA^50^INFORMATION^LA
    SET_CELL_PROPERTY:ROWID|ENABLE|false
    prop=ENABLE value:false
    SET_CELL_PROPERTY:ROWID|WIDTH|5
    prop=WIDTH value:5
    SET_CELL_PROPERTY:ROWID|RESIZE|false
    prop=RESIZE value:false
    SET_CELL_PROPERTY:HIREDATE|BG_COLOR|230,230,255
    prop=BG_COLOR value:230,230,255
    Colulmn: HIREDATE not found. Unable to set property
    SET_CELL_PROPERTY:SAL|BG_COLOR|230,255,255
    prop=BG_COLOR value:230,255,255
    Colulmn: SAL not found. Unable to set property
    SET_CELL_PROPERTY:EMPNO|ENABLE|FALSE
    prop=ENABLE value:FALSE
    Colulmn: EMPNO not found. Unable to set property
    SET_CELL_PROPERTY:EMPNO|FG_COLOR|100,100,100
    prop=FG_COLOR value:100,100,100
    Colulmn: EMPNO not found. Unable to set property
    SET_CELL_PROPERTY:EMPNO|FONT|Tahoma|12|BI
    prop=FONT value:Tahoma
    Colulmn: EMPNO not found. Unable to set property
    SET_CELL_PROPERTY:EMPNO|WIDTH|50
    prop=WIDTH value:50
    Colulmn: EMPNO not found. Unable to set property
    SET_CELL_PROPERTY:EMPNO|MIN_WIDTH|40
    prop=MIN_WIDTH value:40
    Colulmn: EMPNO not found. Unable to set property
    SET_CELL_PROPERTY:EMPNO|MAX_WIDTH|100
    prop=MAX_WIDTH value:100
    Colulmn: EMPNO not found. Unable to set property
    SET_ROW_PROPERTY:HEIGHT|80
    SET_CELL_PROPERTY:PHOTO|WIDTH|200
    prop=WIDTH value:200
    Colulmn: PHOTO not found. Unable to set property
    SETBOUNDS:10,10,600,200
    x=10 y=10 w=600 h=200
    SETTITLE:Content of DEPT table
    SETHEADBG:0,130,255
    SETHEADFG:255,255,102
    SETDATABG:255,255,255
    SETUPDATE:TRUE
    SHOW:FALSE
    seperate=FALSE
    Exception occurred during event dispatching:
    java.lang.NoSuchMethodError
         at oracle.forms.fd.FJTable$2.mousePressed(FJTable.java:1252)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at oracle.ewt.event.tracking.GlassMouseGrabProvider$Disp._redispatchEvent(Unknown Source)
         at oracle.ewt.event.tracking.GlassMouseGrabProvider$Disp.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processEventImpl(Unknown Source)
         at oracle.ewt.event.tracking.GlassMouseGrabProvider$Proxy.processEventImpl(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception occurred during event dispatching:
    java.lang.NoSuchMethodError
         at oracle.forms.fd.FJTable$2.mousePressed(FJTable.java:1252)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at oracle.ewt.event.tracking.GlassMouseGrabProvider$Disp._redispatchEvent(Unknown Source)
         at oracle.ewt.event.tracking.GlassMouseGrabProvider$Disp.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processEventImpl(Unknown Source)
         at oracle.ewt.event.tracking.GlassMouseGrabProvider$Proxy.processEventImpl(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • JTable, how to highlight cells with tooltips?

    Hello all!
    Mine problem is descriped in the topic - I though about custom cell renderer but I dont have an Idea how to change background for many other cells in other rows and don't change background in whole columns. Any of You could help?

    Hey thanks for replying.
    With code like that:
    public class yellowCellRenderer
      extends DefaultTableCellRenderer
      private int whichRow = 0;
      public yellowCellRenderer(int saveToRow)
        this.whichRow = saveToRow;
      public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
        if(this.whichRow == row){
         this.setBackground(Color.YELLOW);  // All columns verified were empty - set our background RED
        return this;
    }and usage:
         comments.add(comment);
         JTable table = getMainTable();
         TableColumnModel colModel = table.getColumnModel();
         for(int i=0;i<comment.length;i++){
             if(!Main.isStringEmpty((String)comment)){
              TableColumn column = colModel.getColumn(i);
              column.setCellRenderer(
                   new yellowCellRenderer(table.getRowCount()-1)
    Every each cell in column gets yellow background... What am I doing wrong?

  • Efficiency improvement in JTable

    I need some suggestions/ways to improve the efficiency of my JTable which is to display huge data and to perform update/insert/delete as fast as 20 per second. To minimize the flickering issue I am using double buffering. I have implement ed my own color render and used data key to row number hashtables to update the rows efficiently.
    I ran a test case in which only insertion of new rows are being done at very high rate wihtout any custom renderors the cpu usage of IE (internet explorer) goes 100 percent on a pentium 4 with 2.8 GHtz processor and 512MB ram
    Eagerly waiting for the response(s)
    Regards

    JTable gives many opportunities for optimization. As you've put in some thoughts,
    pardon me for a more general answer to the public.
    Double buffering can be contra-productive: in the newer versions it is on by default.
    The CellRenderer object renders for every table cell.
    What is important, that repaints are not triggered too soon.
    Ensure that cells do not get repainted needlessly.
    Set the table row heigth to a fixed value.
    Do not use the DefaultTableModel for huge data.
    Ensure that getValueAt is fast.
    You might consider hinting for a large data model.
    Small equal Strings might be mapped to one object (like String.internalize).
    If feel a bit hesitant on String.internalize, as it does not free the JVM of these String constants. So use a HashMap<String, String>.
    HashMap is better than Hashtable, but you must then pay attention to synchronization.
    Threading definitely improves (and complicates) things.
    Make the test in an application, rather than an JApplet.

  • JTable how to set cell ediatble false

    - Can teach me JTable how to set cell ediatble false?
    - And I'm not so understand about following method and sentence...
    addRowSelectionInterval(int index0, int index1)
    Adds the rows from index0 to index1, inclusive, to the current selection.
    - Then what is toggle? What is the usage? How to use?
    - Then how to add one more row in the Jtable?

    - Can teach me JTable how to set cell ediatble false?check the method isCellEditable()
    Use DefaultTableModel
    - And I'm not so understand about following method and sentence...
    addRowSelectionInterval(int index0, int index1)
    Adds the rows from index0 to index1, inclusive, to the current selection.
    - Then what is toggle? What is the usage? How to use?
    - Then how to add one more row in the Jtable?[JTable API|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTable.html]

  • Hide a column in a JTable

    Hi All, hope you can help,
    I want to hide the last column of my table, but still access its data. Inside the last column certain information is present, the cell tooltips.
    In my extended JTable class my method getToolTipText looks like this:
            // implement table cell tool tip.
            public String getToolTipText(MouseEvent e) {
                String tip             = null;
                Point  p               = e.getPoint();
                int    rowIndex        = rowAtPoint(p);
                int    colIndex        = columnAtPoint(p);
                int    realColumnIndex = convertColumnIndexToModel(colIndex);
                if(rowIndex>=0 && rowIndex<=lastRow) {
                    if(realColumnIndex==0) {
                        MiniModel mml = (MiniModel)getValueAt(rowIndex, 5); // exception here
                        tip = "<html>" + replaceCRLFtoBR(mml.getComment()) + "</html>"; // replaceCRLFtoBR = custom method to replace \n by <br>
                    } else {
                        tip = columnTips[realColumnIndex]; // constant
                return tip;
            }As you can see at column 5 an object MiniModel is present containing the tooltip for column 0.
    When I use the method removeColumn on column 5 on my extended JTable variable, I get an java.lang.ArrayIndexOutOfBoundsException at the marked position and in more detail on getValueAt.
    As I read everywhere the actual data is not removed (only from the view) I wonder what I'm doing wrong...
    Michiel

    Thanks for the advice, I will prepare better next time, here is my sscce :
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    public class TableHide extends JFrame {
        private static final String[] colNames    = {"Column 1", "Column 2", "Column 3"};
        private static final String[] colHeadTips = {"Header tip 1", "Header tip 2", "Header tip 3"};
        private ExtTableModel    myTableModel;
        private ExtTable         myTable;
        private JScrollPane      myScrollPane;
        private int              lastRow = 0;
        // for example
        private MiniModel mmlRow1 = new MiniModel(1, "cell comment");
        private MiniModel mmlRow2 = new MiniModel(2, "other cell comment");
        // constructor
        public TableHide() {
            this.setTitle("Table column hide test");
            this.setResizable(true);
            this.setLayout(new BorderLayout());
            // build table containing all extended Model's id and name
            myTableModel = new ExtTableModel(null, colNames);
            myTable      = new ExtTable(myTableModel);
            myTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            myTable.setPreferredScrollableViewportSize(new Dimension(500, 130));
            myTable.setFillsViewportHeight(true);
            myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            myTable.getTableHeader().setReorderingAllowed(false);
            myScrollPane = new JScrollPane(myTable);
            this.add(myScrollPane, BorderLayout.CENTER);
            // add some rows, in real application this is more complex
            myTableModel.insertRow(0, new Object[]{ "Basic string", new Boolean(false), mmlRow1 }); lastRow++;
            myTableModel.insertRow(0, new Object[]{ "Other string", new Boolean(true) , mmlRow2 }); lastRow++;
            myTable.setAutoCreateRowSorter(true);
            myTable.getRowSorter().toggleSortOrder(0);
            // this causes the exception
            myTable.removeColumn(myTable.getColumnModel().getColumn(2));
            this.setSize(new Dimension(500,200));
        // inner class to provide an own table model for the extended Models showed on screen. used for booleans
        class ExtTableModel extends DefaultTableModel {
            public ExtTableModel(Object[][] tableData, String[] columnNames) {
                super(tableData, columnNames);
            public boolean isCellEditable(int row, int col) {
                return false;
            public Class getColumnClass(int column){
                Object value=this.getValueAt(0,column);
                return (value==null?Object.class:value.getClass());
        // inner class to privide column header tooltips and cell tooltips
        class ExtTable extends JTable {
            public ExtTable(ExtTableModel extModel) {
                super(extModel);
            // implement table cell tool tip.
            public String getToolTipText(MouseEvent e) {
                String tip             = null;
                Point  p               = e.getPoint();
                int    rowIndex        = rowAtPoint(p);
                int    colIndex        = columnAtPoint(p);
                int    realColumnIndex = convertColumnIndexToModel(colIndex);
                if(rowIndex>=0 && rowIndex<=lastRow) {
                    if(realColumnIndex==0) {
                        MiniModel mml = (MiniModel)getValueAt(rowIndex, 2);
                        tip = mml.getMml_comment();
                    } else {
                        tip = "Some other tooltip function";
                return tip;
            // implement table header tool tip.
            protected JTableHeader createDefaultTableHeader() {
                return new JTableHeader(columnModel) {
                    public String getToolTipText(MouseEvent e) {
                        Point  p         = e.getPoint();
                        int    index     = columnModel.getColumnIndexAtX(p.x);
                        int    realIndex = columnModel.getColumn(index).getModelIndex();
                        return colHeadTips[realIndex];
        // simplified class for usage inside a cell
        public class MiniModel {
            private int        mml_id;
            private String     mml_comment;
            public MiniModel(int mml_id, String mml_comment) {
                this.mml_id      = mml_id;
                this.mml_comment = mml_comment;
            public String getMml_comment() {
                return mml_comment;
            public String toString() {
                return Integer.toString(mml_id); // called when object is displayed
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    new TableHide().setVisible(true);
    }When you show the last column the program works fine. Goal is to have the last column available since it contains extra information about the row, but not to show it.

  • Dynamically Updating JTable, please help

    I am trying to create an GUI for a java program I wrote to interface with motes running TinyOS. I am having some serious problems creating this because in the JTable tutorial everything is static so I can't figure out how I'm supposed to modify the table from my code. I'm basically reading packets coming in from the serial port and updating several data fields based on what is contained in the packet. I want certain cells in the JTable to reflect the changes that occur in the variables I have, sort of like a debugger would display, but in real time and at full run speed. I tried using the setValueAt function but the problem is the JTable is created in a static method and so I cannot call it from main. I tried moving the section of code that monitors the serial port and updates my data to the createAndShowGUI function, but unfortunately the table will not display unless this function returns, but the program will never return from this function if I move the code there and so I just get a completely grey JTable displayed. I have included the code below, sorry for the length of it but I need some help on this one, I was never taught java and am trying to learn this on my own for research purposes. As it stands now the only error generated by this code is from the following line:
    newContentPane.DataTable.setValueAt("asdfsa",1,1);
    I am not allowed access to newContentPane because it has been dynamically instantiated by createAndShowGUI and I cannot access it through main.
    I'd appreciate any help on this, thank you.
    package net.tinyos.tools;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JComponent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Date;
    import java.io.*;
    import net.tinyos.packet.*;
    import net.tinyos.util.*;
    import net.tinyos.message.*;
    public class BeaconListen extends JPanel {
    private static int MAX_NODES = 10;
         JTable DataTable;
         public BeaconListen(){
         super(new GridLayout(1,0));     
         Object[] ColumnNames = {"Node","PPS","Average PPS","Time Elapsed"};
         Object[][] Data= {
         {"0","","",""},
         {"1","","",""},
         {"2","","",""},
         {"3","","",""},
         {"4","","",""},
         {"5","","",""},
         {"6","","",""},
         {"7","","",""},
         {"8","","",""},
         {"9","","",""},
         DataTable = new JTable(Data,ColumnNames);
         DataTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
         JScrollPane scrollPane = new JScrollPane(DataTable);
    add(scrollPane);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI(){
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("MoteData");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    BeaconListen newContentPane = new BeaconListen();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
         if (args.length > 0) {
         System.err.println("usage: java net.tinyos.tools.BeaconListen");
         System.exit(2);
         public static void main(String args[]) {
         //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
                   PacketSource reader = BuildSource.makePacketSource();
         if (reader == null) {
         System.err.println("Invalid packet source (check your MOTECOM environment variable)");
         System.exit(2);
              int i, total = 0;
         int reset =1;
         int packetcount[] = new int[MAX_NODES];
         int PL[] = new int[MAX_NODES];
         int counter[] = new int[MAX_NODES];
         double RSSI[]= new double[MAX_NODES];
         int signalStrength=0;
         double strengthUnsigned=0;
         int Transition=0;
         int PPS=0;
         int FirstRun=1;
         int packetHold=0;
         double avgPacketCount[] = new double[MAX_NODES];
         int secondsElapsed=0;
         int averageReset=1;
         int totalPacketsReceived[] = new int[MAX_NODES];
         System.out.println("Node Listening");
         try {
         reader.open(PrintStreamMessenger.err);
         for(;;){
              byte[] packet = reader.readPacket();
         if(reset==1)
         for(i=0; i<MAX_NODES; i++)
              packetcount=0;
              PL[i]=0;
              counter[i]=0;     
              if(averageReset==1)
              secondsElapsed=0;
              avgPacketCount[i]=0;
              totalPacketsReceived[i]=0;
         reset =0;
         if(FirstRun==0)
         packetcount[packetHold]++;
         totalPacketsReceived[packetHold]++;
         PPS++;
         FirstRun=0;
         averageReset=0;
         packetcount[packet[6]]++;
         totalPacketsReceived[packet[6]]++;
         PPS++;
         strengthUnsigned = ((int)packet[8])& 0xFF;
         RSSI[packet[6]]=RSSI[packet[6]]+strengthUnsigned;
    if((packet[10]==1 && Transition==1) || (packet[10]==0 && Transition==0))
         secondsElapsed++;
         if(Transition==1)
         Transition=0;
         else
         Transition=1;
         PPS--;
         packetcount[packet[6]]--;
         totalPacketsReceived[packet[6]]--;
         packetHold=packet[6];
         reset=1;
         for(i=0; i<MAX_NODES; i++)
         newContentPane.DataTable.setValueAt("asdfsa",1,1);
              System.out.println("Packet Count for Node " + i + "is: " + packetcount[i]);
              PL[i]=8 - packetcount[i];
              System.out.println("Packet Loss for Node " + i + "is: " + PL[i]);
              avgPacketCount[i]=1.0*totalPacketsReceived[i]/secondsElapsed;
              System.out.println("Avg Packet Count for " + secondsElapsed + " seconds is: " +avgPacketCount[i]);
              if(RSSI[i]!=0)
              RSSI[i]=RSSI[i]/packetcount[i];
              RSSI[i]=3*(RSSI[i]/1024);
              RSSI[i]=(-51.3*RSSI[i])-49.2;
              System.out.println("RSSI(dBm) for node " + i + "is: " + RSSI[i]);
              System.out.println();
              packetcount[i]=0;
              RSSI[i]=0;
         System.out.println("Total Packets Recieved: " + PPS);
         PPS=0;
                   System.out.println();
                   System.out.println();
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         catch (IOException e) {
         System.err.println("Error on " + reader.getName() + ": " + e);

    The best way to update your data is using a TableModel :
    When you instantiate a JTable with an array of objects, it creates a DefaultTableModel which actualy stores your data.
    So, you should create your TableModel, and feed it with the data. Each time the data is updated, the TableModel must notify the JTable, so the new data can be shown :
    here's a simple example
    public class MyModel extends AbstractTableModel
    Object[][] data;
    //you must implement some abstract methods declared in AbstractTableModel
    //the method you use to update the data (you can give it the name you want)
    setData(Object[][] _data)
    data=_data;
    fireTableDataChanged();//method of AbstractTableModel that notifies the data has changed
    public void main(String[] s)
    MyModel tableModel = new MyModel();
    JTable table = new JTable(tableModel);
    JFrame frame = new JFrame();
    frame.getContentPane().add((new JScrollPane()).getViewport().add(table);
    frame.pack();
    frame.setVisible(true);
    tableModel.setData(new Object[][]{{"one", "two"}, {"three", "four"};
    thread.sleep(5000);
    tableModel.setData(new Object[][]{{"five", "six"}, {"seven", "eight};
    You will see the table displaying one, two, three, four, during 5 seconds, and then it will display five, six...

  • JTable without JScrollPane behavior crippled

    I want column width of JTable t1 goes parallel with the width resizing on
    JTable t2. If tables are put in JScrollPanes, this has no problem. But if I put
    those tables in simpler container, which is JPanel in this case, t2 shows a
    funny behavior -- with user's mouse operation on t2 column, their width
    never changes but t1 column width changes properly. Could I have
    succeeded in communicating the funniness with these sentences?
    Please try this code and give cause and solution if you could:
    import java.awt.*;
    import java.beans.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class TableColumnWidthResize{
      JFrame frame;
      JTable t1, t2;
      TableColumnModel tcm1, tcm2;
      Enumeration columns1, columns2;
      String[] t1h = {"Road", "Length", "City"};
      String[][] t1c
       = {{"NW2", "800", "Dora"},
         {"Iban", "600", "Weiho"},
         {"ENE2", "500","Porso"}};
      String[] t2h = {"Flower", "Curse", "Priest"};
      String[][] t2c
        = {{"Fang", "7.00", "EggChar"},
          {"Shaoma", "5.00", "ScaCra"},
          {"Jiao", "4.00", "PorCabb"}};
      public TableColumnWidthResize(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container con = frame.getContentPane();
        con.setLayout(new GridLayout(2, 1));
        t1 = new JTable(t1c, t1h); //target table -- 'resized from t2'
        t2 = new JTable(t2c, t2h); //source table -- 'initiate resize'
        t1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        t2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        /* you can compare two methods of table placement*/
        useScrollPane(t1, t2, con); //works fine
    //    nouseScrollPane(t1, t2, con); //resize behavior weird
        frame.pack();
        frame.setVisible(true);
        tcm1 = t1.getColumnModel();
        tcm2 = t2.getColumnModel();
        columns2 = tcm2.getColumns(); // all columns of t2
        TableColumnListener tcl = new TableColumnListener();
        while (columns2.hasMoreElements()){
          TableColumn tc = (TableColumn)(columns2.nextElement());
          tc.addPropertyChangeListener(tcl);
      class TableColumnListener implements PropertyChangeListener{
        // achieve 'interlocking-column-resizing' from t2 to t1
        public void propertyChange(PropertyChangeEvent pce){
          TableColumn tc = (TableColumn)(pce.getSource());
          int i = tc.getModelIndex();
          tcm1.getColumn(i).setPreferredWidth(tc.getWidth());
      void useScrollPane(JTable ta, JTable tb, Container c){
        JScrollPane jsc1 = new JScrollPane(ta);
        ta.setPreferredScrollableViewportSize(new Dimension(225, 50));
        JScrollPane jsc2 = new JScrollPane(tb);
        tb.setPreferredScrollableViewportSize(new Dimension(225, 50));
        c.add(jsc1); c.add(jsc2);
      void nouseScrollPane(JTable ta, JTable tb, Container c){
        JPanel p1 = new JPanel(); JPanel p2 = new JPanel();
        p1.setLayout(new BorderLayout());
        p2.setLayout(new BorderLayout());
        p1.add(ta.getTableHeader(), BorderLayout.PAGE_START);
        p2.add(tb.getTableHeader(), BorderLayout.PAGE_START);
        p1.add(ta, BorderLayout.CENTER);
        p2.add(tb, BorderLayout.CENTER);   
        c.add(p1); c.add(p2);
      public static void main(String[] args){
        new TableColumnWidthResize();
    }

    Hey hiwa,
    I don't see anything mysterious going on. If you think about it, how many components can we resize at run-time/dynamically with a mouse - none, except for the columns in a JTable, Frames and Dialogs. Note the latter two are top level and answer to no-one (except the screen i guess).
    If you have ever implemented a component that can be 'dragged' and manipulated by the mouse, have you ever done so outside, that is, not using a JScrollPane? I doubt it.
    I do not think it has anything to do with mouse precision. Maybe you are just experiencing undefined behaviour, unreliable behaviour. I imagine the Swing team didn't bother themselves with a usage scenario that would yield lesser results for a simple task. Using AUTO_RESIZE_OFF and requesting more room than the Container has to offer may upset that containers LayoutManager i.e. their algorithms may contain code that will shrink child components to fit, or nab space from sibling components.
    Basically, in my experience, how ever long it takes me to realise it, when Swing goes on the blink it is usually a programming error.
    BTW, did my suggestion work ok?
    Sorry if I come across forceful. I'm glad I read and tested your code - the synchronization effect will be very useful.
    Warm regards,
    Darren

  • Reduction of flicker on JTable (or reliability of setIgnoreRepaint)

    A table in one of our applications receives and logs about 10-20 events per second, and does a fairly good job at this. The problem, however, is when the table is visible the flickering is terrible. Even the header row disappears at times when the table is drawn right over it. Obviously, this is unacceptable.
    Yes - all doubleBuffering is set to true. I've even written a small class which iterates through every component to ensure all doubleBuffering is set to true.
    Attempts to use setIgnoreRepaint on the JFrame, JPanel, JScrollbar, and even the JTable are futile. Each component continues to repaint (and flicker).
    I'm open to any suggestions, at the moment my priority is preventing the header row from occasionally disappearing when the actual table is being drawn over it.

    Here is a simple test using only a single thread. I don't get any flicker. However, I did notice a change in CPU usage after about 10 seconds:
    setIgnoreRepaint(true); // 5%
    setIgnoreRepaint(false) // 1%
    This is the opposite of what I would expect.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableThread extends JFrame
         implements ActionListener, Runnable
         JTable table;
         DefaultTableModel model;
         int count;
         public TableThread()
              String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
              Object[][] data =
                   {new Date(), "A", new Integer(1), new Double(5.1), new Boolean(true)},
                   {new Date(), "B", new Integer(2), new Double(6.2), new Boolean(false)},
                   {new Date(), "C", new Integer(3), new Double(7.3), new Boolean(true)},
                   {new Date(), "D", new Integer(4), new Double(8.4), new Boolean(false)}
              model = new DefaultTableModel(data, columnNames);
              table = new JTable( model );
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setIgnoreRepaint(false);
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              JButton button = new JButton( "Start Thread to Update Table" );
              button.addActionListener( this );
              getContentPane().add(button, BorderLayout.SOUTH );
         public void actionPerformed(ActionEvent e)
              new Thread( this ).start();
              table.requestFocus();
         public void run()
              Random random = new Random();
              while (true)
                   final int row = random.nextInt( table.getRowCount() );
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
    //                         table.setValueAt( new Integer(count++), row, 2);
                             count++;
                             Object[] line =
                                  new Date(),
                                  "A",
                                  new Integer(count),
                                  new Double(5.1),
                                  new Boolean(true)
                                  model.addRow(line);
    //                         table.changeSelection(row, 2, false, false);
                   try { Thread.sleep(50); }
                   catch(Exception e) {}
         public static void main(String[] args)
              TableThread frame = new TableThread();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Cell Editor to limit characters in jtable cell

    Hello Java Gods,
    Can anyone help me or write for me a custom cell editor/renderer to limit the max number of characters in a jtable cell to be 10? By this, I mean, the user should not be able to type more than 10 characters in this particular cell.
    Any help would be greatly appreciated. I have to hand in this code before this evening. So please please help me folks.
    Thanking you all in advance.
    Warm Regards,
    Java Newbie

    Try one of these CellEditors:
    class LimitedEditor extends DefaultCellEditor {
        public LimitedEditor() {
            super(new JTextField());
        public boolean stopCellEditing() {
            String value = ((JTextField) getComponent()).getText();
            if (!value.equals("")) {
                if (value.length() > 10) {
                    ((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
                    JOptionPane.showMessageDialog(null, "String length cannot be bigger than 10");
                    return false;
            return super.stopCellEditing();
        public Component getTableCellEditorComponent(final JTable table, final Object value,
                final boolean isSelected, final int row, final int column) {
            JTextField tf = ((JTextField) getComponent());
            tf.setBorder(new LineBorder(Color.black));
            if (value == null) {
                tf.setText("");
            } else {
                tf.setText(value.toString());
            return tf;
    class LimitedEditor2 extends DefaultCellEditor {
        public LimitedEditor2() {
            super(new JTextField());
            JTextField tf = ((JTextField) getComponent());
            tf.setDocument(new PlainDocument() {
                public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                    int len = getLength();
                    if (len + str.length() > 10) {
                        Toolkit.getDefaultToolkit().beep();
                    } else {
                        super.insertString(offs, str, a);
    }Usage example:
            TableColumn tc = table.getColumnModel().getColumn(1);
            tc.setCellEditor(new LimitedEditor2());]

  • JTable with DefaultTableModel not showing?

    I hope this is SSCE...
    I'm using a defaultTableModel, but I cannot get the Table to show.
    When I just simply put the vectors straight into the table, without using the DefaultTableModel it worked.
    This is the code I have now, the table doesn't show at all?
    I actually couldn't get this example to compile, as it only contains snippets of the code. The real code compiles and runs, but the table just doesn't show. I guess it's all part of the same problem.
    If someone could help me with where I've gone wrong in the usage of the DefaultTableModel, it would be greatly appreciated.
    import java.util.Vector;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.TableModel;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.event.*;
    public class FutureTable extends JTable implements TableModelListener {
         Vector colnames = new Vector();
         Vector inne = new Vector();
         TableModel model;
         JTable table = new JTable();
         public FutureTable(){
              //vector colnames
              colnames.addElement("Date");
              //vector inne
              inne.addElement("example")
              //Adds inne and colnames to the TableModel model
              model = new DefaultTableModel(inne, colnames);
              //sets Table to TableModel model
              table.setModel(model);
              //adds a listener to the table
              table.getModel().addTableModelListener(this);
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    public class FutureTableHolder extends JPanel {
         Vector inne = new Vector();     
         JScrollPane scrollPane;     
         FutureTable theTable = new FutureTable();
         public FutureTableHolder() {          
              //Sets the layout to gridlayout so that the table will fill the panel.
              setLayout(new GridLayout(1,0));
              scrollPane= new JScrollPane(theTable);//ScrollPane
              add(scrollPane);
         }//Ends FutureTableHolder()     
         

    When I just simply put the vectors straight into the table, without using the DefaultTableModel it worked. Well, the code is the same.
    You can use:
    JTable table = new JTable(data, columnNames);or
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    JTable table = new JTable( model );So you obviously have a problem with your code and you are not building the Vectors the same way. Since you did not post a SSCCE, we can't help (Although as noted above your data Vector is empty so there is no data to display).

  • Sort indicator missing on JTable in OSX

    I just added column sorting to the JTables in my app. On windows it works as advertised. On OSX, the table is sorted when I click the headers, but the sort indicator does not show up. So the first time the user clicks a header for a column that's already sorted, it looks like nothing happens. On Windows, they see the sort indicator appear, so they know their action had an effect. Plus, they can see the sort direction at any time.
    Is there perhaps a property I need to set to make the sort indicator appear in OSX? Or is this the way it was designed for OSX?

    I should have mentioned, it's the Java implementation on OSX where the problem occurs. JTable is the Java implementation of an emulated native table control.
    As revealed to me on the [email protected] list, there are some client properties that can be set to specify specific Cocoa behaviors in the Java implementation of certain JComponent classes. The properties are listed and their usage explained here.
    http://developer.apple.com/mac/library/technotes/tn2007/tn2196.html#GENID1
    An Apple engineer pointed out that these are workarounds, as OSX should work out of the box same as Windows. I'll submit a bug report, per his suggestion.
    Here's my implementation of the fix for the problem I encouontered. The following method is called from the JTable constructor, so the methods invoked in it are JTable methods.
    private void setupRowSorter() {
    setAutoCreateRowSorter(true);//Java6 only. For Java 5, create a TableRowSorter and add it to the JTable
    getTableHeader().addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
    getTableHeader().putClientProperty("JTableHeader.selectedColumn", getTableHeader().columnAtPoint(e.getPoint()));
    if (getTableHeader().getClientProperty("JTableHeader.sortDirection") == null) {
    getTableHeader().putClientProperty("JTableHeader.sortDirection", "ascending");
    } else if (getTableHeader().getClientProperty("JTableHeader.sortDirection").equals("ascending")) {
    getTableHeader().putClientProperty("JTableHeader.sortDirection", "decending");//misspelling is required, per Apple documentation
    } else {
    getTableHeader().putClientProperty("JTableHeader.sortDirection", "ascending");
    @Override
    public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub
    @Override
    public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub
    @Override
    public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub
    @Override
    public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

Maybe you are looking for

  • Itunes will not recognize my ipod. How do i fix this?

    Itunes will not recognize my ipod. How do I fix this?

  • IPhone 4 catching fire and lack of support from Apple?

    On Saturday when I was charging my phone I noticed a burning smell and immediately ran over to my iphone and pulled out the charger cable which was glowing red and smoke was coming from both it and my iphone 4. My phone although slightly fire damaged

  • Acrobat 9.0 - how to I keep Sticky Note always maximize

    Acrobat 9.0 How do I keep Sticky Note always maximized. I got one sticky note maximized on open of file but on another file, the sticky note minimized itself. Anyone who can help to keep sticky note always maximized .  Thank you.

  • How to Sync BB Q10 with MS Office Pro Plus Outlook 2013

    In BBLink when I click Contacts/Calendar, then config, the only account I always get is "Contacts Windows" with no other choice. I would like to have access to Outlook contacts, calendar, notes, and to do list, and keep them in sink with the BB termi

  • Buttons using CSS not working properly

    I am using Dreamweaver CS4. I can't get buttons to work properly using CSS. The buttons are supposed to have a red border around them when inactive (a:link). Hovering over the button causes it to change its appearence (this works). Clicking the butto