JTable issues

I'm using JDK 6 and i would be glad to get answers to the following regarding JTable?
1) I am using setAutoCreateRowSorter(true) to enable sorting of my JTable columns.
When i have a sorted column which is editable, how can i prevent the column from getting automatically sorted while editing.
It should only get sorted when the column header is clicked.
Sort the score 1 column of my sample code and try to edit a cell, u'll get the picture of what i mean.
2) While editing JTable, when i press tab or enter, i want the selected cell to clear its contents when i type in a value.
I've tried searching the forum but haven't got a solution. Any forum link that would help is welcome.
Thanks
//class create new class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class TableSample extends JFrame implements ActionListener
     private JButton cancel, count;
     private JTextField filterField;
     private JLabel label;
     private JPanel dataPanel, bPanel, filterPanel;
     private JTable dataTable;
     private TableMap map;
     private DefaultTableModel defModel;
     TableRowSorter tableSorter;
     public TableSample()
          super( "Table Sample" );
          setSize( 450, 400 );
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //setup gui
          filterField = new JTextField();
          filterField.addActionListener(this);
          filterPanel = new JPanel(new BorderLayout());
          filterPanel.add( new JLabel( "Filter" ), BorderLayout.WEST );
          filterPanel.add( filterField, BorderLayout.CENTER );
          bPanel = new JPanel();
          cancel = new JButton( "Close" );
          cancel.addActionListener( this );
          bPanel.add( cancel );
          getContentPane().setLayout( new BorderLayout() );
          dataPanel = new JPanel();
          dataPanel.setLayout( new BorderLayout() );
          //create table
          createTable();
          JScrollPane scrollPane = new JScrollPane(dataTable);
          dataPanel.add( scrollPane, BorderLayout.CENTER );
          //dataPanel.add( ftPanel, BorderLayout.SOUTH );
          getContentPane().add( filterPanel, BorderLayout.NORTH );
          getContentPane().add( scrollPane, BorderLayout.CENTER );
          getContentPane().add( bPanel, BorderLayout.SOUTH );
          setVisible( true );
     public void createTable()
          final String[] columnNames = { "Last Name", "First Name", "Score 1", "Score 2" };
          Object dataObject[][] = { {"Ibrahim", "Musa", "78", "87"}, {"Kapoor", "Vijay", "8", "88"},
                                             {"John", "Smith", "76", "67"}, {"Thaichi", "Vijay", "96", "64"},
                                                                                 {"Ibrahim", "Hama Adama", "86", "68"}};
          defModel = new DefaultTableModel(dataObject, columnNames);
          map = new TableMap(defModel);
          dataTable = new JTable(map);
          dataTable.setAutoCreateRowSorter(true);
          //set 3rd and 4th columns to be editable
          int editableColumns[] = new int[columnNames.length];
          editableColumns[2] = 1;     
          editableColumns[3] = 1;     
          map.setEditableColumns(editableColumns);
          tableSorter = (javax.swing.table.TableRowSorter)(dataTable.getRowSorter());
     public void actionPerformed( ActionEvent e )
          if(e.getSource() == filterField ) //filter
               String key = filterField.getText();
               tableSorter.setRowFilter(RowFilter.regexFilter("(?i)" + key));
          else if( e.getSource() == count )
               label.setText(String.valueOf(tableSorter.getViewRowCount()));
          else
               System.exit(0);
     public static void main( String args[] )
          new TableSample();
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
import java.awt.*;
public class TableMap extends AbstractTableModel
     implements TableModelListener
     protected TableModel model;
     private int[] editableColumns;
     public TableMap() {}
     public TableMap(TableModel model)
          this.model = model;
          model.addTableModelListener(this);
          editableColumns = new int[this.model.getColumnCount()];
     public TableModel getModel()
          return model;
     public void setModel(TableModel model)
          this.model = model;
          model.addTableModelListener(this);
          editableColumns = new int[this.model.getColumnCount()];
     // By default, implement TableModel by forwarding all messages
     // to the model.
     public void setEditableColumns( int[] c )
          editableColumns = c;
     public Object getValueAt(int aRow, int aColumn)
          return model.getValueAt(aRow, aColumn);
     public void setValueAt(Object aValue, int aRow, int aColumn)
          model.setValueAt(aValue, aRow, aColumn);
     //method to determine the default renderer/editor for each cell
     public Class getColumnClass(int c)
          String nn = new String();
          try
               if( model.getValueAt(0, c) == null )
                    return nn.getClass();
               else
                    return model.getValueAt(0, c).getClass();
          catch( ArrayIndexOutOfBoundsException aiobe )
               System.out.println("Exception: " + aiobe.getMessage());
          return nn.getClass();
     public int getRowCount()
          return (model == null) ? 0 : model.getRowCount();
     public int getColumnCount()
          return (model == null) ? 0 : model.getColumnCount();
     public String getColumnName(int aColumn)
          return model.getColumnName(aColumn);
     public void removeRow( int row )
     public boolean isCellEditable(int row, int column)
          int c = editableColumns[column];
          if( c == 0 )
               return false;
          else
               return true;
     public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
          return new Choice();
     // Implementation of the TableModelListener interface,
     // By default forward all events to all the listeners.
     public void tableChanged(TableModelEvent e)
          fireTableDataChanged();
          //fireTableChanged(e);
     //public void tableChanged()
          //fireTableDataChanged();
}

Post to Project Swing next time :)
TableModel myModel = new MyModel();
JTable table = new JTable(myModel);
then implement those 3 methods which AbstractTableModel leaves to user:
class MyModel extends AbstractTableModel {
... implementation here
Studing the three methods, plus the rest already implemented, is a good exercise for you ;)
Bye
Enrico

Similar Messages

  • Tooltip in JTable Issue

    I have a JTable that is returning tooltips for each cell in the table. The tooltips are dynamic based on the data contained in the cell. I only want this data to be shown if the user purosely hovers their mouse over a cell.
    The tooltip works correctly for the first cell they mouse over due to the ToolTipManager.sharedInstance().setInitialDelay( XXXXX ) method.
    The problem is that once it is up, it stays up as they move through the table. I believe the reason that setReshowDelay isn't working is due to the fact that at no point (until it leaves the table) is it over an area that doesn't have a valid tooltip.
    When I leave the table with the mouse and return, the initial delay is again in effect. I want that to happen every time the user moves to a new cell.
    Any ideas?

    I believe the reason that setReshowDelay isn't working Its working. Move you mouse over a cell and let it sit there. The tooltip will show and then hide. Now move your mouse a fex pixels in the same cell. The tooltip will reappear. MouseEvents are generated every time you move the mouse a pixel which affects the way the tooltip is displayed.
    I want that to happen every time the user moves to a new cell.Well then you will need to track the current cell and then every time you leave the cell you will need to hide the tooltip.
    So you would need to add a MouseListener to the table and handle the mouseMoved() event. Use the MouseEvent to calculate the cell you are currently in. When the cell changes you need to hide the tooltip manually. The following code should work:
    Action toolTipAction = component.getActionMap().get("hideTip");
    if (toolTipAction != null)
         ActionEvent hideTip = new ActionEvent(component, ActionEvent.ACTION_PERFORMED, "");
         toolTipAction.actionPerformed( hideTip );
    }

  • Jtable issue

    can anybody help me by saying how many row a jtable hold

    How many rows do you require? I've seen tables with thousands of rows. You can run into rendering problems however.
    Cheers
    DB

  • Frustrated with simple JTable issue....very simple..aggghhhh

    I'm trying to create a JTable with currency fileds, and other types as well. It would display currency format but wipe off the dollar signs when the user edits the field and allow the user to enter numbers without dollar signs.
    I was able to do this for a textfield using the online tutorial but having problem creating it for a JTable.
    This is because the example that I'm using creates the table with its data hardcoded...I need to pass data to the table at runtime.
    If I mod the code's constructor to receive data and columnNames, I'd get a Null pointer error because the the first thing the constructor would try to getRowCount which it references ddata...data is not yet assigned a value.
    Here's the tutorial sample codes...
    public TableDemo() {
    JTable table = new JTable(new MyTableModel());
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = ...//same as before...
    private Object[][] data = ...//same as before...
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    I just need to make this table NOT having the data and columnNames hardcoded...or if someone has some niffty currency edits...
    Thanks so much

    Your question still doesn't make any sense to me. From your last posting I suggested you should be using the DefaultTableModel, since you apparently don't understand how to write your own custom TableModel. The DefaultTableModel allows you to create a TableModel loaded with data or you can create an empty DefaultTableModel and add rows of data to it as required.
    I need to pass data to the table at runtime.Again you seem confused. What is the difference between hardcoding data and reading data from a file at runtime? None.
    The basic coding structure would be:
    a) create TableModel
    b) JTable table = new JTable( model );
    Create a method called createTableModel. In that method you either hardcode a table or add logic to read data from a file, read data froma database. It doesn't matter where the data comes from as long as you createTableModel method returns a TableModel.
    In your last posting I gave you a link to a simple working demo. Start with that as your base code and try to customize it. The code you posted here is useless. We can't solve problems based on a few lines of code.
    Here is another example showing how to add rows of data dynamicallly:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=577919
    Use the "code" tags any time you post code.

  • JTable issues ,help me!

    how do i add an actionlistener that will know when I have clicked a specific row?
    for example, how do i delete a row that is highlighted? can someone guide me to a tutorial that's easy to understand? thank you!

    The listener you want is a selectionListener. For deleting rows you need the selected row and a suitable TableModel.
    This is the table tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • Problems adding info to a JTable

    Hi, list,
    I was figthing all this week with a JTable issue and I haven't more resources to try. I think that it's a complex problem to explain, but I'll try it as well I can.
    SCENARIO:
    - There is a panel with 2 JTables (sqlServerJTable and oracleJTable) and a button (loadSQLServerCampaignAction).
    - Each table has different instances of CampaignTableModel [6 columns].
    - Initially,
    sqlServerJTable.getModel() --> 0 rows
    oracleJTable.getModel() --> 3 rows
    - The button's action show a new panel to register a new instance of CampagnaTableInfo. When push accept in this panel, I catch the CampaignTableInfo object and add it to sqlServerJTable.getModel().
    Simple?
    The problems starts now...
    Randomly, we obtain these issues:
    1) Data added without execeptions [Desired result]
    2) No effect: No data added to sqlServerJTable and no Exceptions
    3) Data added with exceptions
    4) No data added with exceptions
    EXCEPTIONS: With the same CampaignTableInfo object, obtain different index on the exception each time.
    =================================================================================
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 3 >= 2
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
            at javax.swing.plaf.basic.BasicTableHeaderUI.paint(BasicTableHeaderUI.java:609)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143)
            at javax.swing.JComponent.paintComponent(JComponent.java:763)
            at javax.swing.JComponent.paint(JComponent.java:1027)
            at javax.swing.JComponent.paintToOffscreen(JComponent.java:5122)
            at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:285)
            at javax.swing.RepaintManager.paint(RepaintManager.java:1128)
            at javax.swing.JComponent._paintImmediately(JComponent.java:5070)
            at javax.swing.JComponent.paintImmediately(JComponent.java:4880)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:723)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:679)
            at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:659)
            at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
            at java.awt.Dialog$1.run(Dialog.java:1045)
            at java.awt.Dialog$3.run(Dialog.java:1097)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1095)
            at java.awt.Component.show(Component.java:1422)
            at java.awt.Component.setVisible(Component.java:1375)
            at java.awt.Window.setVisible(Window.java:806)
            at java.awt.Dialog.setVisible(Dialog.java:985)
            at es.dap.pac.apps.cargaecsi.view.CargaECSIView.viewDialog(CargaECSIView.java:108)
            at es.dap.pac.apps.cargaecsi.controller.MaestrasCampagnaController.manageCampagnas(MaestrasCampagnaController.java:47)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at org.jdesktop.application.ApplicationAction.noProxyActionPerformed(ApplicationAction.java:662)
            at org.jdesktop.application.ApplicationAction.actionPerformed(ApplicationAction.java:698)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at org.jdesktop.swingx.JXHyperlink.fireActionPerformed(JXHyperlink.java:244)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
            at java.awt.Component.processEvent(Component.java:5806)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4413)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2440)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)=================================================================================
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
            [...]=================================================================================
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
            at java.util.Vector.elementAt(Vector.java:427)
            at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
    [continue...]

    I'll try to show only the relevant code:
    =================================================================================
    CampaignTableInfo (A bean with 6 attributes, setters and getters)
    =================================================================================
    CampaignTableModel
    public class CampagnasTableModel extends MyAbstractTableModel<CampagnaTableInfo> {
        private String columnNames[] = {"Campaña", "Descripción", "Fecha Inicio Campaña",
            "Fecha Inicio Control", "Fecha Final Campaña", "Fecha Disponibilidad"};
        public CampagnasTableModel(List<CampagnaTableInfo> data) {
            this.data = data;
        public int getColumnCount() {
            return columnNames.length;
        @Override
        public String getColumnName(int c) {
            return columnNames[c];
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object result = null;
            if (rowIndex >= this.data.size()) {
                System.err.println("-->");
            } else {
                switch (columnIndex) {
                    case 0:
                        result = this.data.get(rowIndex).getIdCampaña();
                        break;
                    case 1:
                        result = this.data.get(rowIndex).getDsCampaña();
                        break;
                    case 2:
                        if (this.data.get(rowIndex).getFhInicioCampaña() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhInicioCampaña());
                        break;
                    case 3:
                        if (this.data.get(rowIndex).getFhInicioControl() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhInicioControl());
                        break;
                    case 4:
                        if (this.data.get(rowIndex).getFhFinalCampaña() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhFinalCampaña());
                        break;
                    case 5:
                        if (this.data.get(rowIndex).getFhDisponibilidad() != null) {
                            result = DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(this.data.get(rowIndex).getFhDisponibilidad());
                        break;
            return result;
        @Override
        public Class getColumnClass(int c) {
            return String.class;
    }=================================================================================
    MyAbstractTableModel
    public abstract class MyAbstractTableModel<TIPO> extends AbstractTableModel{
        protected List<TIPO> data;
        public List<TIPO> getDataModel() {
            return this.data;
        public int getRowCount() {
            int result = 0;
            if(data != null) {
                result = data.size();
            return result;
        public void addData(TIPO tipo) {
            this.data.add(tipo);
            this.fireTableDataChanged();
    }=================================================================================
    CampagnasPanel
    public class CampagnasPanel extends JPanel {
        private CampagnasService service;
        /** Creates new form CampagnasPanel */
        public CampagnasPanel() {
            this.service = new CampagnasService(this);
            initComponents();
            postInitComponents();
        public void setSQLServerTableModel(List<CampagnaTableInfo> tableModel) {
            CampagnasTableModel campagnasTableModel = new CampagnasTableModel(tableModel);
            this.sqlServerTable.setModel(campagnasTableModel);
            this.sqlServerTable.packAll();
        public void setOracleTableModel(List<CampagnaTableInfo> tableModel) {
            CampagnasTableModel campagnasTableModel = new CampagnasTableModel(tableModel);
            this.oracleTable.setModel(campagnasTableModel);
            this.oracleTable.packAll();
        private void postInitComponents() {
            this.createButton.setAction(CargaECSIController.getInstance().getMaestrasCampañaController().getAction("createCampagna"));
        public CampagnasTableModel getCampagnasTableModel() {
            return (CampagnasTableModel) sqlServerTable.getModel();
    }[continue...]

  • JTable row background change - based on EXTERNAL event

    Greetings folks!
    I'm hoping for some help with a JTable issue. Here's the scenario:
    The app is a point of sale application. The user scans or manually adds an item to the order, which causes a row to appear in the JTable displaying description, price, quantity, etc. The user can then right click a row on the JTable and select an option from the popup menu. If the user selects one of the options, I want to be able to change the background color on that row.
    EVERYTHING I've seen online and researching is based on adding a custom renderer to the jtable which changes the background based on the data in the row. In my case there isn't anything in the row which changes... hence the point of changing the color.
    What I'm looking for is a method which will let me change the background of row x. I'm guessing there isn't a way. I'm hoping someone has a suggestion.
    Thanks in advance,
    John E.
    PS: I'm fairly new to java and working with inherited code, so please no 'you need to redesign the world' type answers unless there's an easier way. :)

    In my case there isn't anything in the row which changesThen how is the table going to know what color to paint the row? Remember painting the row is a dynamic process. You can't just paint it once. You need the ability to repaint the row if for example the table is scrolled and the row is now longer present. Then when the table scrolls again and the row is present you need to be able to repaint the row in your specified color. This means you need some way to tell the table what color the row should be. Which means you need to keep that information somewhere.
    One way to do this is to store the data in the TableModel that indicates that this row should be painted a "different" color. Then your situation is like the examples you have found. You now have some data you can test. This column does not need to be visible in the table since you can remove the TableColumn from the TableColumnModel so the column is not painted.
    Here is a simple posting that shows a better approach to painting row backgrounds withouth using a renderer:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Any way around java.lang.VerifyError in JUTableSortModel.enableColumnSortin

    Hi,
    (JDeveloper 10.1.2) I have created a ADF Client application on top of an POJO business service. The application contains a tabbed pane. The first tab is based on a master data control binding, the second on its details-collection data control - as a JTable.
    When I run the application (from within JDeveloper) , I get a Fatal Exception from the JVM:
    Exception in thread main
    java.lang.VerifyError: oracle.jbo.uicli.jui.JUTableSortModel
         at oracle.jbo.uicli.jui.JUTableBinding.getControlModel(JUTableBinding.java:106)
         at oracle.jbo.uicli.jui.JUPanelBinding.bindUIControl(JUPanelBinding.java:817)
         at amis.view.tabbedPane.FortuneForm.jbInit(FortuneForm.java:287)
         at amis.view.tabbedPane.FortuneForm.setBindingContext(FortuneForm.java:467)
         at amis.view.tabbedPane.FortuneForm.main(FortuneForm.java:375)
    When I swap the JTable for some simple JTextFields, the code runs ok. However, I really like to have a Table. Does anyone have any clue or workaround for this situation? Since the exception originates within the ADF library code, I do not see too many options myself.
    thanks for your help.
    Lucas

    OK, I have been too hasty once more.
    When I create a simple ADF BC Model, drag a ViewObject's Data Control as Table to the ADF JClient pane and run the application, I get the same fatal exception. So it has nothing to do with the Business Service technology, it is a generic ADF JClient JTable issue.
    Question is still: what can I do to get rid of it? Is it just my installation, project setup? Should i create a fresh JDev install? Is there a patch?
    Any help is very welcome.
    Lucas

  • Example (using a TableModel) with RandomAccessFile

    Hi,
    Does anyone know of a good JTable example (using a TableModel) with RandomAccessFile?
    I'm particularly interested to see how the TableModel is setup.
    Also, when my JTable issues calls to the TableModel's "getValueAt()" method - to initialize its empty cells - it appears to call "getValueAt()" using randomly chosen row/column values (rather than filling the cells in "left-to-right"/"top-to-bottom" fashion).
    Is this typical?
    s
    null

    nevermind. I figured it out. thanks!
    null

  • Custom Cell Renderer issue in Custom JTable

    I have CustomeTable extends JTable which renders different UI Components like (JTextField/ ComboBox /JButton/JCheckBox) in *"single column*" so i have overridden *getCellRenderer* and *getCellEditor methods.*
    Now my Custom Table changes contextually by selecting different nodes in JTree similar to Windows Explorer
    *The problem is Some times When i Click Button & then i click other Node which displays other UIComponents old components (Button is painted) instead of new COmponent(JTextfield or ...)*
    *For each UI Renderer i have called its repaint() method still this issue is noticed not frequentlly but yes occasionally.*

    Following are some of my Custom Text / Combo Renderer / Password / Button to display different UI Components @ Column 2 as per my above Code
    private class MyDefaultRenderer implements TableCellRenderer {
            private JTextField l;
            private Border borderPrevious;
            public MyDefaultRenderer() {
                l = new JTextField();
                borderPrevious = l.getBorder();
            public Component getTableCellRendererComponent(JTable table,
                    Object value,
                    boolean isSelected,
                    boolean hasFocus,
                    int row,
                    int column) {
                PropertyInfoType propertyType = propertyInfoList.get(row).getType();
                if (ConfigCommonPropertyPanel.isInputEditable && !propertyInfoList.get(row).isReadOnly()) {
                String tempVal = "";
                if (value != null && value instanceof String) {
                    tempVal = value.toString();
                l.setText(tempVal);
                l.setOpaque(true);
                l.revalidate();
                l.repaint();
                return l;
            public Object getCellEditorValue() {
                return l.getText();
           private class ButtonRenderer implements TableCellRenderer {
            JPanel buttonPanel;
            JButton button;
            public ButtonRenderer() {
                buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                button = new JButton(getAdminUIMsg(168));
                buttonPanel.setOpaque(true);
                buttonPanel.add(button);
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                button.setFont(LNFManager.getThemeForComponent(table).getBodyText());
                buttonPanel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                buttonPanel.revalidate();
                buttonPanel.repaint();
                return buttonPanel;
        private class ButtonEditor extends JButton implements TableCellEditor, ActionListener {
            int rowIndex;
            int columnIndex;
            JTable table;
            JPanel panel;
            public ButtonEditor() {
                super("Validate Database");
                panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                addActionListener(this);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
                rowIndex = row;
                columnIndex = column;
                setOpaque(true);
                panel.setOpaque(true);
                panel.setPreferredSize(new Dimension(getPreferredSize().width, getRowHeight()));
                setFocusable(true);
                panel.repaint();
                panel.add(this);
                return panel;
            public Object getCellEditorValue() {
                return this.isSelected();
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                return true;
            public void cancelCellEditing() {
            public void addCellEditorListener(CellEditorListener l) {
            public void removeCellEditorListener(CellEditorListener l) {
            public void actionPerformed(ActionEvent e) {
                              try{
    // Some Business Logic To check my Database / LDAP Connections on Button Click
                                 }catch( Exception ex){
                                  } finally{
                                            stopCellEditing();
                                            transferFocus();
                   +Shouldnt i call repaint() on a specific Component for a Specific renderer ?+
    My Code works perfectly 99 % of the times ..
    But very rarely when i click My Button On my Custom Table say
    When i click NODE A - which displays different UI in Right Split Info
    Row 2 Column 2 - has Validate Button
    Then i Click NODe B - Which displayes Contextual UI Components
    Row 2 Column 2 should display TextBox (as expected)
    but due to some rendering issue its Displaying same Validate Button
    I have debugged and verified my logic to call renderer is perfect.
    My rest of rows /columns displays appropriate UI Components except the
    position of Button .
    I think after my Button Editor is Invoked & i perform some business logic Button renderer is not getting invoked ???

  • JTable text alignment issues when using JPanel as custom TableCellRenderer

    Hi there,
    I'm having some difficulty with text alignment/border issues when using a custom TableCellRenderer. I'm using a JPanel with GroupLayout (although I've also tried others like FlowLayout), and I can't seem to get label text within the JPanel to align properly with the other cells in the table. The text inside my 'panel' cell is shifted downward. If I use the code from the DefaultTableCellRenderer to set the border when the cell receives focus, the problem gets worse as the text shifts when the new border is applied to the panel upon cell selection. Here's an SSCCE to demonstrate:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.EventQueue;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import sun.swing.DefaultLookup;
    public class TableCellPanelTest extends JFrame {
      private class PanelRenderer extends JPanel implements TableCellRenderer {
        private JLabel label = new JLabel();
        public PanelRenderer() {
          GroupLayout layout = new GroupLayout(this);
          layout.setHorizontalGroup(layout.createParallelGroup().addComponent(label));
          layout.setVerticalGroup(layout.createParallelGroup().addComponent(label));
          setLayout(layout);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
          if (isSelected) {
            setBackground(table.getSelectionBackground());
          } else {
            setBackground(table.getBackground());
          // Border section taken from DefaultTableCellRenderer
          if (hasFocus) {
            Border border = null;
            if (isSelected) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusSelectedCellHighlightBorder");
            if (border == null) {
              border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
            setBorder(border);
            if (!isSelected && table.isCellEditable(row, column)) {
              Color col;
              col = DefaultLookup.getColor(this, ui, "Table.focusCellForeground");
              if (col != null) {
                super.setForeground(col);
              col = DefaultLookup.getColor(this, ui, "Table.focusCellBackground");
              if (col != null) {
                super.setBackground(col);
          } else {
            setBorder(null /*getNoFocusBorder()*/);
          // Set up our label
          label.setText(value.toString());
          label.setFont(table.getFont());
          return this;
      public TableCellPanelTest() {
        JTable table = new JTable(new Integer[][]{{1, 2, 3}, {4, 5, 6}}, new String[]{"A", "B", "C"});
        // set up a custom renderer on the first column
        TableColumn firstColumn = table.getColumnModel().getColumn(0);
        firstColumn.setCellRenderer(new PanelRenderer());
        getContentPane().add(table);
        pack();
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TableCellPanelTest().setVisible(true);
    }There are basically two problems:
    1) When first run, the text in the custom renderer column is shifted downward slightly.
    2) Once a cell in the column is selected, it shifts down even farther.
    I'd really appreciate any help in figuring out what's up!
    Thanks!

    1) LayoutManagers need to take the border into account so the label is placed at (1,1) while labels just start at (0,0) of the cell rect. Also the layout manager tend not to shrink component below their minimum size. Setting the labels minimum size to (0,0) seems to get the same effect in your example. Doing the same for maximum size helps if you set the row height for the JTable larger. Easier might be to use BorderLayout which ignores min/max for center (and min/max height for west/east, etc).
    2) DefaultTableCellRenderer uses a 1px border if the UI no focus border is null, you don't.
    3) Include a setDefaultCloseOperation is a SSCCE please. I think I've got a hunderd test programs running now :P.

  • Issue with re-sizing JTable Headers, JTabbedPane and JSplit pane

    Ok, hopefully I'll explain this well enough.
    In my Swing application I have a split pane, on the left hand side is a JTable and on the right hand is a JTabbedPane. In the tabs of the JTabbedPane there are other JTables.
    In order to make the rows in the JTable on the left and the JTable(s) on the right line up, the Table Header of all the tables is set to the size of the tallest (deepest?) table header.
    Hopefully so far I'm making sense. Now to get to the issue. One of the tables has a number of columns equal to the value on a NumberSpinner (it represents a number of weeks). When this value is changed the table is modified so that it contains the correct number of columns. As the table is re-drawn the table header goes back to its default size so I call my header-resize method to ensure it lines up.
    The problem is this: if I change the number of weeks when selecting a tab other than the one containing my table then everything is fine, the table header is re-sized and everything lines up. If I change the number of weeks with the tab containing the table selected, the column headers stay at their standard size and nothing lines up.
    To make things more complicated, I also put System.out.println's in as every method called in the process to obtain the size of the table header. And every println returned the same height, the height the table header should be.. So I'm really confused.
    Could anyone shed any light on this?
    Thanks.

    Okay I managed to solve the problem by explicitly revalidating and repainting the table header.
    Not sure why it wasnt doing it properly for that table when all the others where fine.
    Oh well...

  • Issue with JTable

    Hi,
    I have a issue with JTable. I am reading an array and populating the cells in the JTable. After editing the cell values, on clicking a button, I update the value in to an array. The probelm is that after editing the value in the cell, if I don't use tab or enter key and move the focus away from the cell, I dont get the updated value when using the getValueAt method. Pleease let me know if there is any workaround for this behaviour.
    Thanks,
    Baskar N

    Just so you understand why that code snippit works, you have to stop or cancel editing before you can get the updated value of a cell.

  • Editable JComboBox in JTable focus issue

    Please look at the sample code below.
    I am using a JComboBox as the editor for a column in the table. When a cell in that column is edited and the user presses enter, the cell is no longer in edit mode. However, the focus is now set on the next component in the scrollpane (which is a textfield).
    If I don't add the textfield and the the table is the only component in the scroll pane, then focus correctly remains on the selected cell.
    When the user exits edit mode, I'd like the table to have focus and for the cell to remain selected. How can I achieve this?
    thanks,
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import javax.swing.plaf.basic.*;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import java.util.EventObject;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TableComboBoxTest extends JFrame {
         protected JTable table;
         public TableComboBoxTest() {
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());
              MyTableModel model = new MyTableModel();
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setSurrendersFocusOnKeystroke(true);
              TableColumnModel tcm = table.getColumnModel();
              TableColumn tc = tcm.getColumn(MyTableModel.GENDER);
              tc.setCellEditor(new MyGenderEditor(new JComboBox()));
              tc.setCellRenderer(new MyGenderRenderer());
              JScrollPane jsp = new JScrollPane(table);
              pane.add(jsp, BorderLayout.CENTER);          
              pane.add(new JTextField("focus goes here"), BorderLayout.SOUTH);
         public static void main(String[] args) {
              TableComboBoxTest frame = new TableComboBoxTest();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(500, 300);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public class MyTableModel extends AbstractTableModel {
              public final static int FIRST_NAME = 0;
              public final static int LAST_NAME = 1;
              public final static int DATE_OF_BIRTH = 2;
              public final static int ACCOUNT_BALANCE = 3;
              public final static int GENDER = 4;
              public final static boolean GENDER_MALE = true;
              public final static boolean GENDER_FEMALE = false;
              public final String[] columnNames = {
                   "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender"
              public Object[][] values = {
                        "Clay", "Ashworth",
                        new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
                        new Float(12345.67), "three"
                        "Jacob", "Ashworth",
                        new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
                        new Float(23456.78), "three1"
                        "Jordan", "Ashworth",
                        new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
                        new Float(34567.89), "three2"
                        "Evelyn", "Kirk",
                        new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
                        new Float(-456.70), "One"
                        "Belle", "Spyres",
                        new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
                        new Float(567.00), "two"
              public int getRowCount() {
                   return values.length;
              public int getColumnCount() {
                   return values[0].length;
              public Object getValueAt(int row, int column) {
                   return values[row][column];
              public void setValueAt(Object aValue, int r, int c) {
                   values[r][c] = aValue;
              public String getColumnName(int column) {
                   return columnNames[column];
              public boolean isCellEditable(int r, int c) {
                   return c == GENDER;
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList()
                   return listBox;
         public class MyGenderRenderer extends DefaultTableCellRenderer{
              public MyGenderRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                   JComboBox box = new JComboBox();
                   box.addItem(value);
                   return box;
         public class MyGenderEditor extends DefaultCellEditor  { // implements CaretListener {
              protected EventListenerList listenerList = new EventListenerList();
              protected ChangeEvent changeEvent = new ChangeEvent(this);
              private JTextField comboBoxEditorTField;
              Object newValue;
              JComboBox _cbox;
              public MyGenderEditor(JComboBox cbox) {
                   super(cbox);
                   _cbox = cbox;
                   comboBoxEditorTField = (JTextField)_cbox.getEditor().getEditorComponent();
                   _cbox.addItem("three");
                   _cbox.addItem("three1");
                   _cbox.addItem("three2");
                   _cbox.addItem("One");
                   _cbox.addItem("two");
                   _cbox.setEditable(true);
                   _cbox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                             System.out.println("\nactionPerformed ");
                             fireEditingStopped();
              public void addCellEditorListener(CellEditorListener listener) {
                   listenerList.add(CellEditorListener.class, listener);
              public void removeCellEditorListener(CellEditorListener listener) {
                   listenerList.remove(CellEditorListener.class, listener);
              protected void fireEditingStopped() {
                   System.out.println("fireEditingStopped called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             System.out.println("calling editingStopped on listener....................");                    
                             listener = (CellEditorListener) listeners;
                             listener.editingStopped(changeEvent);
              protected void fireEditingCanceled() {
                   System.out.println("fireEditingCanceled called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             listener = (CellEditorListener) listeners[i];
                             listener.editingCanceled(changeEvent);
              public void cancelCellEditing() {
                   System.out.println("cancelCellEditing called ");
                   fireEditingCanceled();
              public void addNewItemToComboBox() {
                   System.out.println("\naddNewItemToComboBox called ");
                   // tc - start
                   String text = comboBoxEditorTField.getText();
                   System.out.println("text = "+text);                    
                   int index = -1;
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in cbox = "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");                              
                             index = i;
                             _cbox.setSelectedIndex(index);
                             break;
                   if (index == -1)
                        _cbox.addItem(text);
                        int count = _cbox.getItemCount();
                        _cbox.setSelectedIndex(count -1);
              public boolean stopCellEditing() {
                   System.out.println("stopCellEditing called ");
                   fireEditingStopped();
                   _cbox.transferFocus();
                   return true;
              public boolean isCellEditable(EventObject event) {
                   return true;     
              public boolean shouldSelectCell(EventObject event) {
                   return true;
              public Object getCellEditorValue() {
                   System.out.println("- getCellEditorValue called returning val: "+_cbox.getSelectedItem());
                   return _cbox.getSelectedItem();
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   System.out.println("\ngetTableCellEditorComponent "+value);
                   String text = (String)value;               
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in box "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");     
                             _cbox.setSelectedIndex(i);
                             break;
                   return _cbox;

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • JTable accessibility issues

    I am implementing the accessibility functionality to an application. And I am testing the features using the JAWS screen reader software.
    Now, all of the menus and the component labels are being read by the reader except for when the component in question is an instance of JTable.
    No matter where I shift the focus within the table, the reader always says row 0 and column 0.
    I am unable to fathom the problem. Is this a JDK issue or something wrong with my implementation?
    Thanks in advance.

    I may have a solution (seems to work).
    I implemented a timer and whenever a cell change occurs (through mouseMostionListener) I start my timer (50 ms). when I start the timer (right before, actually) I set a flag instructing my getToolTipText in the JTable to return null. When the timer expires, it sets the flag to let the method fetch the actual tooltip.
    This seems to restart the initial delay when I traverse different cells.
    Any better ideas?

Maybe you are looking for

  • Possible to change sidebar div from left to right?

    I'm just starting to design completely using CSS...very tough to change. I have a home page roughed out with a sidbar nav on the left BUT I'm thinking it may be a bit more mobile friendly if I move it to the right and allow the content to be all the

  • Error message while resizing a file

    Could not complete the Image Size command because of a program error. I find this particularly frustrating since this begun after completing several files successfully.  Happens in PS 2014 CC and the previous version. Both are up to date. This machin

  • Why has Aperture suddenly started "beachballing"?

    It appears that ever since I have started "Vaulting" (Verbatim portable HD); Aperture has become slow and started beachballing every time I launch application. The trainer at the store installed iStat(?) but it hasn't helped me with anything. I am ed

  • Urgent: Multiple DDK's in a WD application

    Hi All, In my application we are using 3 DDK's. On selecting the one entry in 1st DDK the entries in the second DDK should get populated, similarly on selection of one entry the corresponding entries should get populated in 3rd DDK UI element. All th

  • Connecting on a new iMac G5

    Trying to help a friend get his new iMac G5 on to the net, transferred his old setting from his old mac running 10.2.8 which used a usb cable, connected to a external modem/single router which then goes direct to the phone line. But with the new mac'