JTable getValueAt()

I have a few questions/problems with JTables:
I have a jTable that adds a MouseListener and a PropertyChangedListener. For the mouseListener I only implement the mouseClicked() method. But it stills seems to be calling the mouseEntered and mouseExited methods from somewhere. I noticed this because I put a print statement in my getValueAt() method and it prints when I put the mouse over a cell. Any ideas?
Also is there any way to only call getValueAt() when the table data has changed? My application seems to be calling getValueAt() at every possible time... should I be concerned with this, or is this acceptable?I've looked around I can't seem to find the right answer. I tried overriding the valueChanged() method of the JTable class, but I don't know what to do in it when I override it.
I'm sorry if this is really messed up but I can't seem to explain it correctly.
Any help would be appreciated. Thanks.

hey homer,
Well the reason why getValueAt() is called each time a mouseEntered and mouseExited occurs is for tool tips and the drawing of the table. Say for example your user interface drew a yellow box around the current cell that your mouse is over, well in that case the renderer for the cell needs to get the value of the cell to redraw the cell.
I wouldn't be concerned about getValueAt being called over and over. Basicaly every time a cell is rendered, get value at will be drawn, same goes for a column or a row, as the cells in that row or column are redrawn.
I presume your using your own data model and you can't figure out why its called so many times? well hopefuly the above has explained it a bit better. If you ever get into cell rendering you will start to see how the data model is called continualy. its lots of fun :-)
James.

Similar Messages

  • JTable - getValueAt Problem

    I am new to Java and am having a problem with a JTable. I want the user to enter 12 months of rain that will go into an array list. The input sreen is O.K., but I cant retrieve the data or clear the cells. Any suggestings would be appreciated. Here is the code. Thanks Ronnie
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.BorderFactory.*;
    import javax.swing.table.*;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JMenuBar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class GridBagWindow extends JFrame implements ActionListener,
    FocusListener {
    public GridBagWindow() {
    setTitle("User Rainfall Data");
    JComboBox userCboRainCounty, userCboRainYr;
    DefaultTableModel dtmUserRain = new DefaultTableModel();
    JMenuBar userRainJMB = new JMenuBar();
    JMenu userRainfileMenu = new JMenu("File");
    JMenu userRainprintMenu = new JMenu("Print");
    JMenu userRainclearMenu = new JMenu("Clear");
    JMenu userRaintotalsMenu = new JMenu("Totals");
    // Need to add additional menu option because evnet can not be added
    // directly to JMenu
    JMenuItem userRainOpen = new JMenuItem("Open");
    JMenuItem userRainSave = new JMenuItem("Save");
    JMenuItem userRainPrint = new JMenuItem("Print");
    JMenuItem userRainClear = new JMenuItem("Clear");
    JMenuItem userRainTotals = new JMenuItem("Totals");
    userRainJMB.add(userRainfileMenu);
    userRainfileMenu.add(userRainOpen);
    userRainfileMenu.add(userRainSave);
    userRainJMB.add(userRainprintMenu);
    userRainprintMenu.add(userRainPrint);
    userRainJMB.add(userRainclearMenu);
    userRainclearMenu.add(userRainClear);
    userRainJMB.add(userRaintotalsMenu);
    userRaintotalsMenu.add(userRainTotals);
    userRainOpen.addActionListener(this);
    userRainSave.addActionListener(this);
    userRainPrint.addActionListener(this);
    userRainClear.addActionListener(this);
    userRainTotals.addActionListener(this);
    setJMenuBar(userRainJMB);
    Container contentPane = getContentPane();
    setFont(new Font("Arial", Font.BOLD, 16));
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    contentPane.setLayout(gridbag);
    int width = 800;
    int height = 500;
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width - width) / 2;
    int y = (screen.height - height) / 2;
    setBounds(x, y, 600, 600);
    setJMenuBar(userRainJMB);
    JLabel userRainLblCounty = new JLabel(
    " County");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 0, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 25, 1, 1);
    gridbag.setConstraints(userRainLblCounty, c);
    contentPane.add(userRainLblCounty);
    userCboRainCounty = new JComboBox();
    userCboRainCounty.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainCounty.setBackground(Color.white);
    buidConstraints(c, 3, 0, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainCounty, c);
    userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainCounty);
    String[] header = { "Jan", "Feb", "Mar", "Apr", "May", "June",
    "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Total" };
    DefaultTableModel dftModel = new DefaultTableModel(header, 1);
    JTable userRainTable = new JTable(dftModel);
    userRainTable.setEnabled(true);
    JScrollPane scrollPane = new JScrollPane(userRainTable);
    buidConstraints(c, 1, 1, 3, 1, 0, 0);
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(10, 10, 1, 1);
    gridbag.setConstraints(scrollPane, c);
    contentPane.add(scrollPane);
    JLabel userRainLblRain = new JLabel("Rain (in)");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 1, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userRainLblRain, c);
    contentPane.add(userRainLblRain);
    userRainTable
    .setPreferredScrollableViewportSize(new Dimension(600, 20));
    JLabel userRainLblRainYr = new JLabel("Rainfall Years");
    userRainLblRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.SOUTH;
    c.insets = new Insets(0, 1, 1, 1);
    gridbag.setConstraints(userRainLblRainYr, c);
    contentPane.add(userRainLblRainYr);
    userCboRainYr = new JComboBox();
    userCboRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainYr.setBackground(Color.white);
    buidConstraints(c, 1, 2, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainYr, c);
    // userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainYr);
    JLabel userRainLblTitle = new JLabel("Title");
    userRainLblTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    // c.insets = new Insets(1, 14,1,1);
    gridbag.setConstraints(userRainLblTitle, c);
    contentPane.add(userRainLblTitle);
    JTextField userRainTxtTitle = new JTextField(18);
    userRainTxtTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 3, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 1, 1, 1);
    gridbag.setConstraints(userRainTxtTitle, c);
    contentPane.add(userRainTxtTitle);
    JLabel userLblRainBlank = new JLabel(" ");
    buidConstraints(c, 0, 3, 4, 4, 0, 0);
    c.insets = new Insets(15, 15, 1, 1);
    gridbag.setConstraints(userLblRainBlank, c);
    contentPane.add(userLblRainBlank);
    JButton userBtnRainDefault = new JButton(" Default ");
    userBtnRainDefault.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainDefault.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 1, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainDefault, c);
    contentPane.add(userBtnRainDefault);
    JButton userBtnRainCancel = new JButton(" Cancel ");
    userBtnRainCancel.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainCancel.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 2, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new Insets(15, 0, 0, 0);
    gridbag.setConstraints(userBtnRainCancel, c);
    contentPane.add(userBtnRainCancel);
    JButton userBtnRainOK = new JButton(" O.K ");
    userBtnRainOK.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainOK.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 3, 4, 1, 1, 20, 20);
    c.insets = new Insets(15, 0, 0, 150);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainOK, c);
    userBtnRainOK.addActionListener(this);
    contentPane.add(userBtnRainOK);
    // //User Definded Cold Protection
    // Input Combo Box for County Selection, two counties per line
    userCboRainCounty.addItem("CHARLOTTE");
    userCboRainCounty.addItem("CITRUS");
    userCboRainCounty.setSelectedIndex(5);
    userCboRainYr.addItem(String.valueOf(1));
    userCboRainYr.addItem(String.valueOf(5));
    userCboRainYr.addItem(String.valueOf(10));
    userCboRainYr.setSelectedIndex(-1);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pack();
    setVisible(true);
    void buidConstraints(GridBagConstraints c, int gx, int gy, int gw, int gh,
    int wx, int wy) {
    c.gridx = gx;
    c.gridy = gy;
    c.gridwidth = gw;
    c.gridheight = gh;
    c.weightx = wx;
    c.weighty = wy;
    public void focusGained(FocusEvent af) {
    // if(af.getSource() == userRainTable){
    // userRainTable.setBackground(Color.yellow);
    public static void main(String args[]) {
    GridBagWindow window = new GridBagWindow();
    public void actionPerformed(ActionEvent evt) {
    String actionName = evt.getActionCommand();
    System.out.println("Button \"" + actionName + "\" was pressed.");
    // userRainTable.getValueAt(1,1);
    if (actionName == "Clear") {
    for (int i = 0; i > 14; i++) {
    // userRainfallTable.setValueAt(0, 1 , 1);
    System.out.println("Yes Continue");
    if (actionName == "Totals") {
    System.out.println("Yes Continue");
    }

    Hello Ronnie,
    this is a nice little piece of code. ;-)
    No chance of reducing it a little bit just to show the problem?
    And what about making it at least to compile error free? (Just tried on 1.5_06)
    Also place tags around to make it more readable.
    Regards
    J�rg                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Refresh jTable after inserting new data into the Database

    Hey all,
    I'm using Netbeans 6.5 to create a Desktop Application which is connected to a Java DB (Derby).
    The first simple steps were all very successfull:
    Create the jTable and bind it to the Database => everything works fine. When the application starts it correctly shows all data from the database.
    The problem starts when I try to insert new data to the database.
    For that reason I've created textfields and a button "Save". When I press the button it successfully inserts the data to the database but they are not displayed in the jTable (when the application starts they are all there, they are not updated at runtime) . I've tried table.invalidate() and table.repaint() but they just don't work.
    Any help will be GREATLY appreciated. But please have in mind that most of the code is Netbeans-generated and most of it not editable.
    Many thanks in advance.
    George

    Once again you are right my friend. I jumped to conclusion way too fast, when I shouldn't. (Give me a break, I've been busting my head with this well over a week). The response I saw when I did that was that indeed a line is added to the jTable. Because I falsly set the index of the object to be added to be second to last the row appeared on the table, what I didn't see at the time was that the last one disappeared. Hmm...
    A new adventure begins...
    So after a few hours of messing around with it here are my observations:
    1) It was not an observable list. When I add the new element with employeesList.add(newEmp); , the table gets notified but a get a bunch of exceptions:
    xception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 84, Size: 84
            at java.util.ArrayList.RangeCheck(ArrayList.java:546)
            at java.util.ArrayList.get(ArrayList.java:321)
            at org.jdesktop.swingbinding.impl.ListBindingManager$ColumnDescriptionManager.validateBinding(ListBindingManager.java:191)
            at org.jdesktop.swingbinding.impl.ListBindingManager.valueAt(ListBindingManager.java:99)
            at org.jdesktop.swingbinding.JTableBinding$BindingTableModel.getValueAt(JTableBinding.java:713)
            at javax.swing.JTable.getValueAt(JTable.java:1903)
            at javax.swing.JTable.prepareRenderer(JTable.java:3911)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
            at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1974)
            at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1897)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:154)
            at javax.swing.JComponent.paintComponent(JComponent.java:743)
            at javax.swing.JComponent.paint(JComponent.java:1006)
            at javax.swing.JViewport.blitDoubleBuffered(JViewport.java:1602)
            at javax.swing.JViewport.windowBlitPaint(JViewport.java:1568)
            at javax.swing.JViewport.setViewPosition(JViewport.java:1098)
            at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.vsbStateChanged(BasicScrollPaneUI.java:818)
            at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(BasicScrollPaneUI.java:807)
            at javax.swing.DefaultBoundedRangeModel.fireStateChanged(DefaultBoundedRangeModel.java:348)
            at javax.swing.DefaultBoundedRangeModel.setRangeProperties(DefaultBoundedRangeModel.java:285)
            at javax.swing.DefaultBoundedRangeModel.setValue(DefaultBoundedRangeModel.java:151)
            at javax.swing.JScrollBar.setValue(JScrollBar.java:441)
            at javax.swing.plaf.basic.BasicScrollBarUI.scrollByUnits(BasicScrollBarUI.java:907)
            at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.mouseWheelMoved(BasicScrollPaneUI.java:778)
            at javax.swing.plaf.basic.BasicScrollPaneUI$MouseWheelHandler.mouseWheelMoved(BasicScrollPaneUI.java:449)
            at apple.laf.CUIAquaScrollPane$XYMouseWheelHandler.mouseWheelMoved(CUIAquaScrollPane.java:38)
            at java.awt.Component.processMouseWheelEvent(Component.java:5690)
            at java.awt.Component.processEvent(Component.java:5374)
            at java.awt.Container.processEvent(Container.java:2010)
            at java.awt.Component.dispatchEventImpl(Component.java:4068)
            at java.awt.Container.dispatchEventImpl(Container.java:2068)
            at java.awt.Component.dispatchMouseWheelToAncestor(Component.java:4211)
            at java.awt.Component.dispatchEventImpl(Component.java:3955)
            at java.awt.Container.dispatchEventImpl(Container.java:2068)
            at java.awt.Component.dispatchEvent(Component.java:3903)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
            at java.awt.Container.dispatchEventImpl(Container.java:2054)
            at java.awt.Window.dispatchEventImpl(Window.java:1801)
            at java.awt.Component.dispatchEvent(Component.java:3903)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 84, Size: 84
            at java.util.ArrayList.RangeCheck(ArrayList.java:546)
            at java.util.ArrayList.get(ArrayList.java:321)
            at org.jdesktop.swingbinding.impl.ListBindingManager$ColumnDescriptionManager.validateBinding(ListBindingManager.java:191)
            at org.jdesktop.swingbinding.impl.ListBindingManager.valueAt(ListBindingManager.java:99)
            at org.jdesktop.swingbinding.JTableBinding$BindingTableModel.getValueAt(JTableBinding.java:713)
            at javax.swing.JTable.getValueAt(JTable.java:1903)
            at javax.swing.JTable.prepareRenderer(JTable.java:3911)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
    ... and a lot morewhich from my poor understanding means that the jTable succesfully notices the change but it is not able (??) to adjust to the new change. What is more interesting is that when I plainly add the element to the end of the list (without an idex that is), a blank row appears at the end of my Table. The weird thing is that I've bound the table to some text fields below it, and when I select that empty row all the data appear correctly to the text fields.
    I tried going through:
                    org.jdesktop.observablecollections.ObservableCollections.observableList(employeesList).add(newEmp);as well as
                    help = org.jdesktop.observablecollections.ObservableCollections.observableListHelper(employeesList);
                    help.getObservableList().add(newEmp);
                    help.fireElementChanged(employeesList.lastIndexOf(newEmp));and
                    obsemployeesList = org.jdesktop.observablecollections.ObservableCollections.observableList(employeesList);
                    obsemployeesList.add(newEmp);and I still get the same results (both the exeptions and the mysterious empty row at the end of the table
    So, I'm again in terrible need of your advice. I can't thank you enough for the effort you put into this.
    Best regards,
    George
    Edited by: tougeo on May 30, 2009 11:06 AM
    Edited by: tougeo on May 30, 2009 11:21 AM
    Edited by: tougeo on May 30, 2009 11:30 AM

  • Adding data dynamically to JTable with a filter - getting error

    Hello,
    I am using JTable, and adding data and displaying it worked fine
    until I tried adding a filter,
    can anyone tell me what am I doing wrong or
    why am I getting this Error?
    The Error message
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:501)
            at javax.swing.JTable.convertRowIndexToModel(JTable.java:2620)
            at javax.swing.JTable.getValueAt(JTable.java:2695)
            at javax.swing.JTable.prepareRenderer(JTable.java:5712)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2075)
            at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1977)
            at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1773)
            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.paintChildren(JComponent.java:864)
            at javax.swing.JComponent.paint(JComponent.java:1036)
            at javax.swing.JViewport.paint(JViewport.java:747)
            at javax.swing.JComponent.paintChildren(JComponent.java:864)
            at javax.swing.JComponent.paint(JComponent.java:1036)
            at javax.swing.JComponent.paintToOffscreen(JComponent.java:5122)
            at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:277)
            at javax.swing.RepaintManager.paint(RepaintManager.java:1217)
            at javax.swing.JComponent._paintImmediately(JComponent.java:5070)
            at javax.swing.JComponent.paintImmediately(JComponent.java:4880)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:803)
            at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
            at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
            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:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)I am also using my own class that extends "AbstractTableModel"
    as TableModel,
    public class MyTableModel extends AbstractTableModel  {
        ArrayList<TableData> tableData=new ArrayList<TableData>(10);
        String[] columnNames=new String[]{"S/N"," Time (mili)","SD","SA","SSAP","DA","DSAP","FC","DATA"};   
        public void addRow(TableData data){
            tableData.add(data);
            fireTableDataChanged();
        @Override
        public int getRowCount() {
            return tableData.size();
        public TableData getRow(int i){
            return tableData.get(i);
        @Override
        public int getColumnCount() {
            return columnNames.length;
        @Override
        public String getColumnName(int col) {
                return columnNames[col];
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return tableData.get(rowIndex).getValue(columnIndex);
        }The Row Filter class
    class myRowFilter extends RowFilter<MyTableModel,Integer>{
            @Override
            public boolean include(Entry<? extends MyTableModel, ? extends Integer> entry) {
                // Entry < SomeCostumTableModel , Integer> entry   ; Integer =Identifier= Row Number
                boolean frame_type;
                MyTableModel model=entry.getModel();
                TableData data=model.getRow(entry.getIdentifier());
                frame_type=((SD1&&data.SD==TableData.SD1) ||
                                             (SD2&&data.SD==TableData.SD2) ||
                                             (SD3&&data.SD==TableData.SD3) ||
                                             (SD4&&data.SD==TableData.SD4) ||
                                             (SC&&data.SD==TableData.SC) );
               return frame_type;
        }and How I add the filter to the Table
        private MyTableModel myTableModel=new MyTableModel();
        private RowSelectionListener rowSelectionListener=new RowSelectionListener();
        TableRowSorter<MyTableModel> sorter=new TableRowSorter<MyTableModel>(myTableModel);
        private FilterFrame filterFrame=new FilterFrame(this);
        // then in the constructor of the main frame
        // I call this
            sorter.setRowFilter(filterFrame.filter);
            MainTable.setRowSorter(sorter);
            sorter.setSortsOnUpdates(true);Edited by: YellowMurdoch on Nov 17, 2009 6:31 AM
    Edited by: YellowMurdoch on Nov 17, 2009 6:31 AM

    Thanks for noting that.
    you mean like this?
    public void addEntry(TableData data){
            myTableModel.addRow(data);
            javax.swing.SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                        myTableModel.fireTableRowsInserted(0,0);
        }both work,
    would putting "invokeLater" inside "addEntry" somehow mess other things?
    i guess that means addRow() is not supposed to update the table graphically?
    Edited by: YellowMurdoch on Nov 17, 2009 9:30 AM
    Edited by: YellowMurdoch on Nov 17, 2009 9:33 AM

  • Update JTable cells via setValueAt

    Hello all,
    I'm trying to implement a setValueAt method using an arrayList.....no success.What listeners should I have set up(For JTable or my table model)? I am new at this and I'm trying to update the JTable cells after a query from some db. Could anyone help?
    When trying to change the a value in the table I get these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at CachingResultSetTableModel.getValueAt(CachingResultSetTableModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

    I would think that everone who starts off with JTable will have a couple of concept problems. I am also going thru this learnig curve. It looks to me ( the blind leading the blind etc) like your basic table has strange data in it. The problem is occuring when the JTable is trying to setup the data from the table model.
    I don't think its anything to do with setValueAt.
    I kept going back to TableMap, TableSorter and JDBCAdaptor examples and copying the code from them to come right.> I debug by putting a System.out .... in all the methods until I get to where the code is giving trouble.
    Good luck [email protected]
    Hello all,
    >
    I'm trying to implement a setValueAt method using an
    arrayList.....no success.What listeners should I have
    set up(For JTable or my table model)? I am new at
    this and I'm trying to update the JTable cells after a
    query from some db. Could anyone help?
    When trying to change the a value in the table I get
    these errors:
    "Exception occurred during event dispatching:
    java.lang.ClassCastException: java.lang.String
    at
    CachingResultSetTableModel.getValueAt(CachingResultSetT
    bIleModel.java:37)
    at javax.swing.JTable.getValueAt(JTable.java:1711)
    at
    javax.swing.JTable.prepareRenderer(JTable.java:3530)"
    public void setValueAt(Object avalue, int r, int c){
    if(r < cache.size()){
    row[c] = (Object[])cache.set(r, avalue);
    fireTableCellUpdated(r, c);
    }//setValueAt
    *********For reference here's the getValueAt
    method*************************
    public Object getValueAt(int r, int c){
    if(r < cache.size()){
    row = (Object[])cache.get(r);
    return row[c];
    else
    return null;
    }//getValueAt

  • Problem in adding row in JTable

    Hi,
    I was trying to add a row in a table when the add button is clicked. But i am missing something that's why i am getting some exceptions.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.JButton;
    import java.util.Vector;
    import java.awt.event.*;
    public class TableDemo extends JFrame implements ActionListener {
            int rows = 1;
            int cols = 4;
            JTable table = new JTable();
            TModel model = new TModel();
            JButton button = new JButton("Add");
            Object[][] values = {
                                          {"Java","Linux","Hello","World"}
            class TModel extends DefaultTableModel {
                    public boolean isCellEditable(int parm1, int parm2){
                            return true;
                    public int getRowCount(){
                            return rows;
                    public int getColumnCount(){
                            return cols;
                    public void setValueAt(Object aValue, int aRow, int aColumn) {
                            values[aRow][aColumn] = aValue;
                    public Object getValueAt(int aRow, int aColumn) {
                            return values[aRow][aColumn];
                    public String getColumnName(int column) {
                            return "Error " + column;
            public TableDemo(String title){
                    super(title);
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout());
                    table.setModel(model);
                    // Make the columns with gradually increasing width:
                    String columnName[] = {"Column", "Operator", "Values", "Logical"};
                    for (int i = 0; i < columnName.length; i++) {
                            TableColumn column = new TableColumn(i);
                            int width = 100+20*i;
                            column.setPreferredWidth(width);
                            column.setHeaderValue(columnName);
    model.addColumn(column);
    // Create the table, place it into scroll pane and place
    // the pane into this frame.
    JScrollPane scroll = new JScrollPane();
    // The horizontal scroll bar is never needed.
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.getViewport().add(table);
    button.addActionListener(this);
    panel.add(scroll, BorderLayout.CENTER);
    panel.add(button, BorderLayout.SOUTH);
    getContentPane().add(panel, BorderLayout.CENTER);
    public void actionPerformed(ActionEvent ae) {
    if(ae.getSource() == button) {
    Vector tempRow = new Vector();
    model.setRowCount(rows++);
    tempRow.addElement("One");//new JComboBox());
    tempRow.addElement("Two");
    tempRow.addElement("Three");
    tempRow.addElement("Four");
    model.addRow(tempRow);
    model.fireTableDataChanged();
    System.out.println("Hi");
    public static void main(String[] args) {
    TableDemo frame = new TableDemo("Table double click on the cell to edit.");
    frame.setSize(new Dimension(640, 400));
    frame.validate();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    The code is generating the follwoing exception when add button is clicked :
    java.lang.ArrayIndexOutOfBoundsException: 2 > 1
    at java.util.Vector.insertElementAt(Vector.java:557)
    at javax.swing.table.DefaultTableModel.insertRow(DefaultTableModel.java:343)
    at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:319)
    at com.saijava.TableDemo.actionPerformed(TableDemo.java:96)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5100)
    at java.awt.Component.processEvent(Component.java:4897)
    at java.awt.Container.processEvent(Container.java:1569)
    at java.awt.Component.dispatchEventImpl(Component.java:3615)
    at java.awt.Container.dispatchEventImpl(Container.java:1627)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
    at java.awt.Container.dispatchEventImpl(Container.java:1613)
    at java.awt.Window.dispatchEventImpl(Window.java:1606)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:480)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    java.lang.ArrayIndexOutOfBoundsException: 1
    at com.saijava.TableDemo$TModel.getValueAt(TableDemo.java:55)
    at javax.swing.JTable.getValueAt(JTable.java:1771)
    at javax.swing.JTable.prepareRenderer(JTable.java:3724)
    at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1149)
    at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
    at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
    at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
    at javax.swing.JComponent.paintComponent(JComponent.java:541)
    at javax.swing.JComponent.paint(JComponent.java:808)
    at javax.swing.JComponent.paintChildren(JComponent.java:647)
    at javax.swing.JComponent.paint(JComponent.java:817)
    at javax.swing.JViewport.paint(JViewport.java:722)
    at javax.swing.JComponent.paintChildren(JComponent.java:647)
    at javax.swing.JComponent.paint(JComponent.java:817)
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4787)
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4740)
    at javax.swing.JComponent._paintImmediately(JComponent.java:4685)
    at javax.swing.JComponent.paintImmediately(JComponent.java:4488)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:189)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:478)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    Umm. A few tips:
    1) You should NOT instantiate objects / initialize variables outside the constructor. And please use access-modifiers.
    2) Do not make your main-class extend JFrame or implement ActionListener. Instead create a JFrame in main and use an anonymous inner class as an ActionListener
    3) Why are you extending DefaultTableModel? To set the the column names as Error1, etc.? You can set the column names by using an appropriate constructor for JTable or by using setColumnIdentifiers(...). See the API.
    4) The actual problem most likely lies here:
    int rows = 1;
    int cols = 4;Why are you defining these outside the TableModel?

  • How to hide the column in JTable

    Hi
    I want to hide a column . But I would be needing the data in that column. ( I have 4 columns )
    I want to hide 4th column
    I have done these steps
    MyTableModel  myTableModel= new  MytableModel(t);
    myTable  = new JTable(myTableModell);                 
    mTable.getColumnModel().removeColumn(myTable.getColumnModel().getColumn(3));When I trying to read the column 1 value it is giving the exception
    myTable.getValueAt(row,3).toString();It is giving the arrayboundexception
    Can anybody tell me what is the correct method to do ?
    Thanks and regards
    Anshuman

    Thanks for reply .
    I have taken the value as the convertRowToModel
    WalterLaan wrote:
    You get an exception because the table doesn't have a column at index anymore, but you can still ask the model.
    table.getModel().getValueAt(table.convertRowToModel(row), 3);
    But it is giving the same error
    java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
         at javax.swing.JTable.convertColumnIndexToModel(Unknown Source)
         at javax.swing.JTable.getValueAt(Unknown Source)Edited by: techie_india on Jul 6, 2009 10:38 PM

  • How can i make hidden column in JTable

    hi, how can i make hidden column in JTable,
    basically i have a ID field in JTable, i have to use this ID , but i also dont want to show this ID in JTable.
    any idea how ??

    staiji its not working
    i did this :
    first :
    TableColumnModel columnModel =
    usersTable.getColumnModel();TableColumn column =
    columnModel.getColumn(1);
    usersTable.removeColumn(column);
    then when i trying to get this :
    Integer userId =
    (Integer)usersTable.getValueAt(UserBrowser.this.usersTa
    le.getSelectedRow(), 0);
    it not give me ID column's value .
    i have a column in JTable like :
    ID | Username | First name | Last name
    i want to hide ID column , but get this ID's value
    when user clicks on JTable row.Hi, if you would read the documentation about JTable.getValueAt(...) you will find, that there is a significant difference between this method and the datamodels getValueAt(...) method. JTables getValueAt(...) method interprets column-index as index in its TableColumnModel - in your TableColumnModel there is no column any longer that holds ID values, therefore you were not able to get it by JTable.getValueAt(...). Do not use these methods for the purpose you want it for - you will also get the wrong values, if the user has repositioned columns - the column index is always interpreted as index in the currently used TableColumnModel and IS NOT A MODELINDEX.
    greetings Marsian

  • JTable cell color

    I use the following custom DefaultTableCellRenderer:
    ------------------------CustomTableCellRenderer-------------------
    import java.awt.Component;
    import java.awt.Color;
    import java.awt.Font;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    public class CustomTableCellRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent( JTable jTable, Object value,boolean isSelected, boolean hasFocus, int row,int col)
         super.getTableCellRendererComponent(jTable, value, false,
         true, row, col);
         setHorizontalAlignment(CENTER);
         if(row!=0 && !(jTable.getValueAt(row-1,col).toString().equals(value.toString()))) {
              setBackground(new Color(255,220,220));
         return this;
    -----------------main class-----------------------------------------------
    TableCellRenderer cell = new CustomTableCellRenderer();
         table.setDefaultRenderer( Object.class, cell );
    The above scheme works fine where I want to color a cell every time a change/transition occurs among the values in a particular column for each column in the table.
    The problem is, in the resulting table, all the cells appear selected and I am unable to select a set of rows or columns by clicking/dragging and trying to create a rectangular rubberband.
    Why is it not allowing me to treat this as a regular JTable instance where upon clicking any cell, the whole row gets selected?
    I suspect the 3rd and 4th arguments in the following statement, I tried all boolean combinations for it, but in vain:
    super.getTableCellRendererComponent(jTable, value, false,
         true, row, col);
    any help?

    You need to override the prepareRenderer method of the TableRenderer with something like this:
            table = new JTable(myTableModel) {
                public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int colIndex) {
                    Component c = super.prepareRenderer(renderer, rowIndex, colIndex);
                    // Set color lightyellow, lightred (inverted ones) or just like the rest of the cells.
                    String cellContent = myTableModel.getValueAt(rowIndex, 4).toString();
                    if (table.isCellSelected(rowIndex, colIndex)) {
                        // nothing to do or maybe setSelectionBackground or further if/else if/else for selected cells.
                    } else if (colIndex == 4 && cellContent.equals("content1")) {
                        c.setBackground(new Color(255, 220, 200));
                    } else if (colIndex == 4 && cellContent.contains("content2")) {
                        c.setBackground(new Color(255, 255, 220));
                    } else {
                        c.setBackground(table.getBackground());
                    return c;
            };If you don't know that c is a TableCellRenderer component you'll need instanceof check.

  • Adding rows to Jtable with spanded cells

    I have a jtable with multiple spanded cells. I am using a custom jtable(the code is in http://www2.gol.com/users/tame/swing/examples/JTableExamples4.html) but i need insert a new row when you click on a button.
    I doing this:
    jtable.getModel().addRow(vector);
    but it throws an exception:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 11 >= 11
    at java.util.Vector.elementAt(Unknown Source)
    at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
    at javax.swing.JTable.getValueAt(Unknown Source)
    at javax.swing.JTable.prepareRenderer(Unknown Source)
    at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paintCell(MultiSpanCellTableUI.java:96)
    at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paintRow(MultiSpanCellTableUI.java:68)
    at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paint(MultiSpanCellTableUI.java:39)
    at javax.swing.plaf.ComponentUI.update(Unknown Source)
    at javax.swing.JComponent.paintComponent(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JViewport.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Can anybody help me

    I am using the same code in http://www.codeguru.com/java/articles/139.shtml but it thorws the same exception.
    I need a solution it is urgent

  • Jtable need help with column name

    hi, i'm currently working on a project where my jtable grab data from the database.
    as for the where clause i am thinking if i can get the column name as the field name in the table. However, I would like to hide the field name from the user.
    So, I'm here to kindly ask if there is a way that i can display the column name that is hidden from the field name.
    thanks in advance.

    actually, I am thinking of a lazy way to add the 'where' clause for my sql statement.
    so, instead of detecting which column that is related to the field i can just use the columns header name as my field. But on the other hand, I'd like to hide my field name from the user .
    For say my field name is "emp_no" but it is displayed as "Employee No" to the user. and when i do my sql statement i can do something like this:
    select * from emp_details where + jtable.getcolumnname(i).tostring() + = jtable.getvalueat(j,i)
    is there a way i can do it so???
    thanks again. and thanks for the reply

  • JTable (yes, again) with TableSorter - exception in the second request.

    While using the TableSorter the data is populated correctly and I manage to sort the items (beautiful)
    say I ask for a list of items and the return result is 20 and the second time I'll ask for a list of items where the return result is greater than 20 items an error will occur with reference to: java.lang.ArrayIndexOutOfBoundsException : 10
    com.softme.jtable.Renderer.TableSorter.modelIndex(TableSorter.java:207)
    com.softme.jtable.Renderer.TableSorter.getValueAt(TableSorter.java:249)
        public int modelIndex(int viewIndex)
             return getViewToModel()[viewIndex].modelIndex;         
        }any idea why this happens?

    I am also getting this same Exception... I have tried various things to prevent this from happening. I can state that in my case I am running table model updates in a SwingWorker Thread to create a visual effect on the screen (rows are being processed and updated as the user watches)
    Could this be a problem of the JTable object accessing the getValue method to update the screen at the same time as the Thread is accessing it for the test value locking the model index object?
    Just a thought.
    This problem is very annoying to the user as it only happens once-in-a-while. Thanks for any help on this problem.
    Here is the changes I made to the code and the error I get... As you can see I test for NULL before running the line, it passes and then STILL gives a NullPointerExcpetion... this is why I am thinking Thread issue...
    public int modelIndex(int viewIndex) {
             Row[] row = getViewToModel();
             if (row == null) System.out.println("?: " +viewIndex);
             if (row != null) {
                  return row[viewIndex].getModelIndex(); //this line is throwing the NPE
             else
                  return -1;
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at com.adriansteel.rpg.rpgSubfileSorter.modelIndex(rpgSubfileSorter.java:323)
         at com.adriansteel.rpg.rpgSubfileSorter.getValueAt(rpgSubfileSorter.java:363)
         at javax.swing.JTable.getValueAt(Unknown Source)
         at javax.swing.JTable.prepareRenderer(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
         at javax.swing.plaf.ComponentUI.update(Unknown Source)
         at javax.swing.JComponent.paintComponent(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source)
         at javax.swing.JComponent.paintDoubleBuffered(Unknown Source)
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(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.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • TableSorter errors when adding new data

    so here is the deal:
    I am using the TableSorter.java helper class with DefaultTableModel
    from: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    It works great when the data is static and I get it for the first time. however, occationally, when adding new data I get a NullPointerException error.
    in use:
    DefaultTableModel.addRow()
    DefaultTableModel.removeRow() and
    DefaultTableModel.insertRow() methods.
    Error:
    java.lang.ArrayIndexOutOfBoundsException: 5
         at com.shared.model.TableSorter.modelIndex(TableSorter.java:294)
         at com.shared.model.TableSorter.getValueAt(TableSorter.java:340)
         at javax.swing.JTable.getValueAt(Unknown Source)
         at javax.swing.JTable.prepareRenderer(Unknown Source)...
    code problem I:
        public Object getValueAt(int row, int column)
            return tableModel.getValueAt(modelIndex(row), column);
        }code problem II:
        public int modelIndex(int viewIndex)
                 return getViewToModel()[viewIndex].modelIndex;     
        }TableSroter class:
    package com.shared.model;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    * TableSorter is a decorator for TableModels; adding sorting
    * functionality to a supplied TableModel. TableSorter does
    * not store or copy the data in its TableModel; instead it maintains
    * a map from the row indexes of the view to the row indexes of the
    * model. As requests are made of the sorter (like getValueAt(row, col))
    * they are passed to the underlying model after the row numbers
    * have been translated via the internal mapping array. This way,
    * the TableSorter appears to hold another copy of the table
    * with the rows in a different order.
    * <p/>
    * TableSorter registers itself as a listener to the underlying model,
    * just as the JTable itself would. Events recieved from the model
    * are examined, sometimes manipulated (typically widened), and then
    * passed on to the TableSorter's listeners (typically the JTable).
    * If a change to the model has invalidated the order of TableSorter's
    * rows, a note of this is made and the sorter will resort the
    * rows the next time a value is requested.
    * <p/>
    * When the tableHeader property is set, either by using the
    * setTableHeader() method or the two argument constructor, the
    * table header may be used as a complete UI for TableSorter.
    * The default renderer of the tableHeader is decorated with a renderer
    * that indicates the sorting status of each column. In addition,
    * a mouse listener is installed with the following behavior:
    * <ul>
    * <li>
    * Mouse-click: Clears the sorting status of all other columns
    * and advances the sorting status of that column through three
    * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
    * NOT_SORTED again).
    * <li>
    * SHIFT-mouse-click: Clears the sorting status of all other columns
    * and cycles the sorting status of the column through the same
    * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
    * <li>
    * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
    * that the changes to the column do not cancel the statuses of columns
    * that are already sorting - giving a way to initiate a compound
    * sort.
    * </ul>
    * <p/>
    * This is a long overdue rewrite of a class of the same name that
    * first appeared in the swing table demos in 1997.
    * @author Philip Milne
    * @author Brendon McLean
    * @author Dan van Enckevort
    * @author Parwinder Sekhon
    * @version 2.0 02/27/04
    public class TableSorter extends AbstractTableModel
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
            public int compare(Object o1, Object o2)
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator()
            public int compare(Object o1, Object o2)
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter()
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel)
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader)
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState()
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel()
            return tableModel;
        public void setTableModel(TableModel tableModel)
            if (this.tableModel != null)
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null)
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader()
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader)
            if (this.tableHeader != null)
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer)
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null)
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())
        public boolean isSorting()
            return sortingColumns.size() != 0;
        private Directive getDirective(int column)
            for (int i = 0; i < sortingColumns.size(); i++)
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column)
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column)
            return getDirective(column).direction;
        private void sortingStatusChanged()
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null)
                tableHeader.repaint();
        public void setSortingStatus(int column, int status)
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE)
                sortingColumns.remove(directive);
            if (status != NOT_SORTED)
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size)
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE)
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting()
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator)
            if (comparator == null)
                columnComparators.remove(type);
            else
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column)
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null)
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType))
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel()
            if (viewToModel == null)
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++)
                    viewToModel[row] = new Row(row);
                if (isSorting())
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
                 return getViewToModel()[viewIndex].modelIndex;     
        private int[] getModelToView()
            if (modelToView == null)
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++)
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount()
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount()
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column)
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column)
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column)
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column)
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column)
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable
            private int modelIndex;
            public Row(int index)
                this.modelIndex = index;
            public int compareTo(Object o)
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();)
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null)
                        comparison = 0;
                    } else if (o1 == null)
                        comparison = -1;
                    } else if (o2 == null)
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0)
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener
            public void tableChanged(TableModelEvent e)
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting())
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null)
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter
            public void mouseClicked(MouseEvent e)
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1)
                    int status = getSortingStatus(column);
                    if (!e.isControlDown())
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority)
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y)
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth()
                return size;
            public int getIconHeight()
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column)
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive
            private int column;
            private int direction;
            public Directive(int column, int direction)
                this.column = column;
                this.direction = direction;
    }any input will be appreciated.
    thanks
    Peter

    The code you posted doesn't help us at all. Its just a duplicate of the code from the tutorial. The custom code is what you have written. For example do you update the TableModel from the Event Thread? Do you update the SortModel or the DefaultTableModel? If you actually provide your test code and somebody has already downloaded the sort classes, then maybe they will test your code against the classes. But I doubt if people will download the sort classes and create a test program just to see if they can duplicate your results (at least I know I'm not about to).

  • Cell request focus problem

    Hi,
    I have jtable with two column. Column A and column B. I type string "stupid" in column A. Then when I change the cell by pressing Enter or right arror or other arrow, it suddenly check the value in column A with the string "clever". Then it is not same. So my Jtable put focus in that cell again and hightlight the string "stupid" so when user type something, the string "stupid" is cleared and replaced by whatever the user typed. The user is forced to type string "clever" otherwise he cann't go anywhere.
    How do I do that? ( put focus on certain cell and hightlight the string )
    I don't know how to hightlight but this is how I try to give the focus to that cell:
    JTable.getModel().addTableModelListener( new TableModelListener() {
        public void tableChanged(TableModelEvent tme) {
            final int column = tme.getColumn();
            final int row = tme.getFirstRow();
            if(column==0) {
                try {
                    if((String)JTable.getValueAt(row,column)!="clever") {
                            JTable.setEditCell(row,column);
                catch( SQLException e ) {
                    e.printStackTrace();
    });With this code, I looked up in that cell. Cann't do anything. Cann't push the button. I just have to kill it by operating system.
    Thank you.

    A TableModelListener listens for changes that have already been made to the table, so you should not be doing error checking here.
    Here is one way (I don't know if its the best) that allows you to do some error checking:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class TableEdit extends JFrame
         TableEdit()
              JTable table = new JTable(5,5)
                   public void changeSelection(int row, int column, boolean toggle, boolean extend)
                        if (! isEditing())
                             super.changeSelection(row, column, toggle, extend);
                        else
                             DefaultCellEditor editor = (DefaultCellEditor)getCellEditor();
                             editor.getComponent().requestFocusInWindow();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollpane = new JScrollPane(table);
              getContentPane().add(scrollpane);
              //  Use a custom editor
              TableCellEditor fce = new FiveCharacterEditor();
              table.setDefaultEditor(Object.class, fce);
         class FiveCharacterEditor extends DefaultCellEditor
              FiveCharacterEditor()
                   super( new JTextField() );
                   ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
              public boolean stopCellEditing()
                   try
                        String editingValue = (String)getCellEditorValue();
                        if(editingValue.length() != 5)
                             ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
                             getComponent().requestFocusInWindow();
                             JOptionPane.showMessageDialog(
                                  null,
                                  "Please enter string with 5 letters.",
                                  "Alert!",JOptionPane.ERROR_MESSAGE);
                             return false;
                   catch(ClassCastException exception)
                        return false;
                   return super.stopCellEditing();
              public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.black));
                   return c;
         public static void main(String [] args)
              JFrame frame = new TableEdit();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • NullPointerException in 1.4.2 but not in  1.4.1

    Am I going nuts or is there anyone else who experiense strange NullPointerExceptions when running code with JRE 1.4.2 that was once compiled with javac 1.4.1? The code compiles fine with 1.4.1 and runns fine in java 1.4.1, but when using 1.4.2 I get NullPointerExceptions at strage places like JTable.getValueAt for example. There seams to be some kind of diffrence in the behaviour of JComboBox also. Is there something in the new release 1.4.2 that I have missed?

    Any ideas anyone? I seem to have pretty consistent behaviour in a couple of forms - I've stripped out a lot of code and now the overloaded paint does nothing.
    Under java 1.4.2 nothing is painted (as expected) but under 1.5 the window paints!!
    Why??? It seems almost like AWT decides it's going to paint regardless, although it shouldn't.
    I've also noticed that under 1.5 if you move another application over the top of the window, it DOESN'T repaint areas that have needed it (after the initial paint), so in this situation it IS seeing (and obeying) the code in my overloaded paint.
    I tried overloading paintAll(...) with an empty implementation and sure enough under 1.4.2 nothing is painted, but under 1.5 it is painted; but also in this case when I move another application over the top of the window, it DOES repaint!!
    What gives, is this a JVM, compiler, swing or EDT bug??
    Getting desperate...

Maybe you are looking for

  • Is Adobe Media Encoder like Compressor?

    Is it best to export a finished sequence in a lossless format and then encode for distribution through Media Encoder?  Is AVI/UT a good choice for the initial export? Thanks, James

  • Using an exteral hard drive to edit movies

    Hello, I need some help. I have a iBook G4 and am running OS X 10.3.9. I have a lot of footage that I want to import and edit in imovie. I do not have enough hard drive space on my laptop to do that. I would like to buy and external hard drive to edi

  • Icon problem in photoshop cs4

    when I place a tool icon  such as the move or hand over a picture it shows up three times exp: ( ### ) how can I correct this problem?  to show only one exp: ( # )  using Photoshop  cs4

  • V$session help

    Hi All, I Queried v$session it showned many inactive session. SID SERIAL# USERNAME MACHINE STATUS 172 131 CLOSINGCOST KAVNIYA\KTS-WS-HP-02 INACTIVE 173 1817 CLOSINGCOST KAVNIYA\KTS-WS-HP-05 INACTIVE 174 487 CLOSINGCOST KAVNIYA\KTS-WS-HP-02 INACTIVE 1

  • Run time error in Service entry sheet

    Hi Experts When I create a Service Purchase Order & when I enter a Service Entry sheet using ML81N, When I save it I am getting a run time error (Short dump has not been completely stored (too big) ).Could you please tell me how to overcome to this p