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?

Similar Messages

  • Problem in adding JComboBox in JTable

    Hi,
    I was trying to put some comboxes in a jtable. The problem is I am not able to add combo boxes in the 1st and 2nd column. But its adding from the 3rd column. What can be wrong in the following code?
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.*;
    * TableRenderDemo is just like TableDemo, except that it
    * explicitly initializes column sizes and it uses a combo box
    * as an editor for the Sport column.
    public class TableRenderDemo1 extends JPanel {
        private boolean DEBUG = true;
            DefaultTableCellRenderer renderer =  new DefaultTableCellRenderer();
        public TableRenderDemo1() {
            //super(new GridLayout(1,0));
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 250));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Set up column sizes.
            initColumnSizes(table);
            //Fiddle with the Sport column's cell editors/renderers.
            setUpNameColumn(table, table.getColumnModel().getColumn(3));
            //Fiddle with the Sport column's cell editors/renderers.
            setUpSportColumn(table, table.getColumnModel().getColumn(4));
            //Add the scroll pane to this panel.
            add(scrollPane);
            String strPlaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            try {
                    UIManager.setLookAndFeel(strPlaf);
                    SwingUtilities.updateComponentTreeUI(scrollPane);
            } catch(Exception e) {
                    e.printStackTrace();
         * This method picks good column sizes.
         * If all column heads are wider than the column's cells'
         * contents, then you can just use column.sizeWidthToFit().
        private void initColumnSizes(JTable table) {
            MyTableModel model = (MyTableModel)table.getModel();
            TableColumn column = null;
            Component comp = null;
            int headerWidth = 0;
            int cellWidth = 0;
            Object[] longValues = model.longValues;
            TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
            for (int i = 0; i < 5; i++) {
                column = table.getColumnModel().getColumn(i);
                comp = headerRenderer.getTableCellRendererComponent(
                                     null, column.getHeaderValue(),
                                     false, false, 0, 0);
                headerWidth = comp.getPreferredSize().width;
                comp = table.getDefaultRenderer(model.getColumnClass(i)).
                                 getTableCellRendererComponent(
                                     table, longValues,
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    comboBox.setVisible(true);
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    public void setUpNameColumn(JTable table, TableColumn nameColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("One");
    comboBox.addItem("Two");
    comboBox.addItem("Three");
    comboBox.addItem("Four");
    comboBox.addItem("Five");
    comboBox.setVisible(true);
    nameColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    nameColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    private Object[][] data = {
    {"Mary", "Saikat", "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Srinath", "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Sheela", "Knitting", new Integer(2), new Boolean(false)},
    {"John", "Yashwant", "Something", new Integer(5), new Boolean(true)},
    {"Harry", "Jay", "Playing", new Integer(1), new Boolean(true)},
    public final Object[] longValues = {"Sharon", "Campione",
    "None of the above",
    new Integer(20), Boolean.TRUE};
    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];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    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) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TableRenderDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    TableRenderDemo1 newContentPane = new TableRenderDemo1();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Thanks in advance.

    First, I don't see where you are tying to set the combo box on the first two columns. I only see it for the 3 and 4.
    Also why are you putting combo boxes in columns that are not 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;
            }

  • Help with adding rows to JTable

    Could any body help me with the following problem:
    I have created form where I use JTable.Initially I should show 5 rows in JTable. User can enter data into the cells.And commit I should store the data in database.
    My problem is how to dynamically add rows to JTable as user is entering the data. And how to retain the data in the cells when it is entered.
    Right now when user edits a cell and tabs to next one the data in previous cell disappears.
    Its Urgent can anybody help me
    Thanks in advance
    Babu

    The number of rows, number of columns, etc, are all determined by the TableModel used in the JTable.
    What is the easiest solution is to subclass AbstractTableModel adding methods to support your dynamic row adding/deleting/etc that you need. If you go to the javadoc for JTable, there's a link to a tutorial which contains most of what you need to know.
    - David

  • Problem in deleting Rows of JTable after sorting it

    Hi all,
    I'm getting problems in Removing Row(s) after sorting a JTable.
    Please find the code snippets at this URL. Thanks for your time...
    http://forum.java.sun.com/thread.jsp?forum=31&thread=459736&start=15&range=15&hilite=false&q=

    Hi Abhijeet,
    I tried it the way you said using
         wdContext.nodeBirhtday_List().nodeItab().moveFirst();
         //     loop backwards to avoid index troubles
         for (int i = n - 1; i >= 0; --i)
              current_date  = wdContext.nodeBirhtday_List().nodeItab().currentItabElement().getGbdat().getDate();
              current_month = wdContext.nodeBirhtday_List().nodeItab().currentItabElement().getGbdat().getMonth();
              if (( current_date != date_today ) && ( current_month != month_today ))
                   wdContext.nodeBirhtday_List().nodeItab().removeElement(wdContext.nodeBirhtday_List().nodeItab().
                                  getElementAt(i));                
              wdContext.nodeBirhtday_List().nodeItab().moveNext();     
    It adds records...
    According to Valerys Solution, the IPrivate<CustomController> doesnt show me the required nodes. and gives me 'Unable to resolve' error.
    Can you please suggest where I am going wrong
    Regards
    Abdullah

  • Problem in adding rows in a table

    Hello All ,
    I am having a strange problem in adding table rows here . All things seems to be in place . But when i click the button nothing happens . I have worked on much more complex tables and added rows safely but i cant understand what's happening here . I have saved the form as Dynamic XML form , interactive form , I have set the pagination of the repeating rows . But Heck !!! It's not working at all . I am totally confused . More over while i drag the table from the object palette an error appears and LC closes down .But when i click on the table at the toolbar and inserted table over there then it shows no error . What's happening ?? Any help is greatly appreciated .
    Script : form1.Page1.Subform1.Button1::click - (JavaScript, client)
    form1.Page1.Subform1.Table1.Row4.instanceManager.addInstance(1);
    Thanks .
    Bibhu.

    Hi,
    The way you described reminded me of another thread, where the index was not straightforward: Saving finished Form duplicates some subForms
    You can post your form to Acrobat.com, hit the Share and Publish buttons when prompted and then copy / paste the link here.
    Niall

  • 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

  • Problem in adding image in jtable cells

    hi all.
    im creating a swing application using netbeans 6.0.
    i want to display image in cells of one column.
    for that i set an "image icon" directly to that cell in the "default table model", in that case it is displaying the path of that image in that cell!
    then i created a new label, and set the image as icon of that label. added that label in that cell. in this case it is printing label.tostring() to that cell!!
    please help.
    thanks in advance.

    You need to override getColumnClass to return Icon.class for the column containing the icon. A code snippet that demonstrates how you might do this:      table = new JTable (new DefaultTableModel (data, colNames) {
             public Class getColumnClass (int columnIndex) {
                switch (columnIndex) {
                   case 0: return Calendar.class;
                   case 1: return String.class;
                   case 2: return Icon.class;
                   //case 2: return Boolean.class;
                return null;
          });luck, db

  • Word VBA Macro problem with adding rows to table for BAPI call

    Hello all,
    I have code in Word macro which is reading file from the disk and converting it to binary. This binary should be inserted in the internal table (Dim As object) for further posting. Code is modified from the note 945682.
    Here is the code:
    Sub Read_File(FileNameFull As String)
    Dim oBinaryDataTab As Object
    Dim oBinaryDataRow As Object
    Dim lBytesToRead As Long
    Dim iNumChars, i As Integer
    Dim s1022, s2044, sX As String
    Dim fs, f, ts As Object
    Dim ReadFile As String
    ' Actually does the work of uploading the document in 1022 byte pieces.
    ReadFile = 0
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(FileNameFull)
    Set ts = f.OpenAsTextStream(1, -2)
    lBytesToRead = f.Size
    ReadFile = f.Size
    Do While ts.AtEndOfStream <> True
    If lBytesToRead < 1022 Then
    iNumChars = lBytesToRead
    Else
    iNumChars = 1022
    End If
    s1022 = ts.Read(iNumChars)
    s2044 = ""
    For i = 1 To Len(s1022)
    sX = Hex$(CByte(Asc(Mid(s1022, i, 1))))
    If Len(sX) = 1 Then
    sX = "0" + sX
    End If
    s2044 = s2044 + sX
    Next i
    Set oBinaryDataRow = oBinaryDataTab.Rows.Add
    oBinaryDataRow("LINE") = s2044
    lBytesToRead = lBytesToRead - iNumChars
    Loop
    End Sub
    But on the row "Set oBinaryDataRow = oBinaryDataTab.Rows.Add" code just stopped to work.
    Can somebody give me a hint how to proceed?
    I also tried to Dim oBinaryDataTable As Table and oBinaryDataRow as Row with the same result.
    oBinaryDataTable will be used as to post file to SAP system without GUI FTP connection. Because of that it must be converted to binary form.
    TIA
    Gordan
    P.S. Message to Moderator: Please, be so kind, and put the message in the proper forum if this is not this one.

    Self Resloved

  • Problem with adding a new row in JTable

    Hi,
    I've created a JTable using DefaultTableModel with DefaultTableModel(Object[][] obj,Object[] col) constructor.I've written actionListener for a JButton which should add new row to the tablemodel.Now, the listener adds the row to the model.But its throwing an ArrayOutofBoundsException and the added row is not visible unless I click on any column of the table.
    Kindly help me to resolve this problem
    TIA
    Regards
    Gopi

    Thanks a lot for the reply. Here is the complete code
    TableImpl.java
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import java.util.Vector;
    public class TableImpl extends JFrame {
    DefaultTableModel dataModel;     // TableModel Variable
    /* Constructor to add table and button to the frame     */
    TableImpl() {
              getContentPane().setLayout(null);
              setSize(800,600);
              myModel();
              final JTable table = new JTable(dataModel);
              JScrollPane scrollpane = new JScrollPane(table);
              getContentPane().add(scrollpane);
              scrollpane.setBounds(10,10,700,300);
              TableColumn tcCol = table.getColumnModel().getColumn(1);
              /* Adding ComboBox to the CellEditor of Column 2 of table     */
              JComboBox jcbComboBox = new JComboBox();
              final ReturnVector vctDBAccess = new ReturnVector();
              jcbComboBox.addItem(vctDBAccess.vctGetOidList().elementAt(0).toString());
              jcbComboBox.addItem(vctDBAccess.vctGetOidList().elementAt(2).toString());
              jcbComboBox.addItem(vctDBAccess.vctGetOidList().elementAt(4).toString());
              tcCol.setCellEditor(new DefaultCellEditor(jcbComboBox));
              /*     Adding Listener for Table      */
              dataModel.addTableModelListener(new TableModelListener() {
                   public void tableChanged(TableModelEvent e) {
              /* Columns Manipulation */
                        if(dataModel.getColumnName(e.getColumn()).equals("Second")) {
                        int iRow = e.getFirstRow();
                        int iColumn = e.getColumn();
                        String strColName = dataModel.getColumnName(iColumn);
                        String strData = (String)dataModel.getValueAt(iRow,iColumn);
                        String strNextColumn = dataModel.getColumnName(iColumn+1);
                        dataModel.setValueAt(vctDBAccess.vctGetOidList().elementAt(vctDBAccess.iGetIndex(strData)+1),iRow,iColumn+1);
              /* Adding button to Frame     */
              JButton jbInsert = new JButton("Insert");
              /* Adding new row to the Tablemodel -- Probelm is here     */
              jbInsert.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e){
                        try {
                   Object[] nrow = {"what", "ever", "you"};
                   dataModel.addRow(nrow);
                   }catch(Exception ex) {
                   System.out.println("Exception at adding row = " + ex);
    getContentPane().add(jbInsert);
    jbInsert.setBounds(100,350,100,20);
    addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                   System.exit(0);
         /* Method to initialise new tablemodel     */
         public void myModel() {
              Object[][] data = { {new Integer(10),"two","three"},
                                                 {new Integer(5),"two","three"},
                                                 {new Integer(4),"two","three"},
              String[] col = { "First", "Second", "Third"};
              dataModel = new DefaultTableModel(data,col);
    public static void main(String arg[]) {
              TableImpl ct = new TableImpl();
              ct.setVisible(true);
    /* Class that returns a Vector of String for populating ComboBox entries and
              for getting the index of a particular element of the vector          */
    class ReturnVector {
                   Vector vctOidName=null;
                   ReturnVector() {
                        this.vctOidName = new Vector();
                        vAddOidList();
                   public void vAddOidList() {
                        String[] dbResult = {      "system", "1.3.6.1.2.1.1" ,
                                                      "interface", "1.3.6.1.2.1.2" ,
                                                      "snmp", "1.3.6.1.2.1.3" };
                        for(int i=0;i<dbResult.length;i++) {
                             System.out.println("Value = " + dbResult);
                             vctOidName.addElement(dbResult[i]);
                   public Vector vctGetOidList() {
                        return vctOidName;
                   public int iGetIndex(String strData) {
                        System.out.println("Index = " + vctOidName.indexOf(strData));
                        return vctOidName.indexOf(strData);

  • Problem in adding/deleting rows in JTable

    I am trying to add /remove rows from JTable whose first column is JButton and others are JComboBox's.If no rows are selected,new row is added at the end.If user selects some row & then presses insert button,new row is added below it.Rows can only be deleted if user has made some selection.Kindly help me,where i am making mistake.If any function is to be used.My code is as follows....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class JButtonTableExample extends JFrame implements ActionListener{
    JComboBox mComboLHSType = new JComboBox();
    JComboBox mComboRHSType = new JComboBox();
    JLabel mLabelLHSType = new JLabel("LHS Type");
    JLabel mLabelRHSType = new JLabel("RHS Type");
    JButton mButtonDelete = new JButton("Delete");
    JButton mButtonInsert = new JButton("Insert");
    JPanel mPanelButton = new JPanel();
    JPanel mPanelScroll = new JPanel();
    JPanel mPanelCombo = new JPanel();
    DefaultTableModel dm ;
    JTable table;
    int currentRow = -1;
    static int mSelectedRow = -1;
    public JButtonTableExample()
    super( "JButtonTable Example" );
    makeForm();
    setSize( 410, 222 );
    setVisible(true);
    private void makeForm()
    this.getContentPane().setLayout(null);
    mPanelCombo.setLayout(null);
    mPanelCombo.setBorder(new LineBorder(Color.red));
    mPanelCombo.setBounds(new Rectangle(1,1,400,30));
    mLabelLHSType.setBounds(new Rectangle(26,5,71,22));
    mComboLHSType.setBounds(new Rectangle(83,5,100,22));
    mLabelRHSType.setBounds(new Rectangle(232,5,71,22));
    mComboRHSType.setBounds(new Rectangle(292,5,100,22));
    mPanelCombo.add(mLabelLHSType,null);
    mPanelCombo.add(mComboLHSType,null);
    mPanelCombo.add(mLabelRHSType,null);
    mPanelCombo.add(mComboRHSType,null);
    mPanelScroll.setLayout(null);
    mPanelScroll.setBorder(new LineBorder(Color.blue));
    mPanelScroll.setBounds(new Rectangle(1,28,400,135));
    mPanelButton.setLayout(null);
    mPanelButton.setBorder(new LineBorder(Color.green));
    mPanelButton.setBounds(new Rectangle(1,165,400,30));
    mButtonInsert.setBounds(new Rectangle(120,5,71,22));
    mButtonDelete.setBounds(new Rectangle(202,5,71,22));
    mButtonDelete.addActionListener(this);
    mButtonInsert.addActionListener(this);
    mPanelButton.add(mButtonDelete,null);
    mPanelButton.add(mButtonInsert,null);
    dm = new DefaultTableModel();
    //dm.setDataVector(null,
    //new Object[]{"Button","Join","LHS","Operator","RHS"});
    dm.setDataVector(new Object[][]{{"","","","",""}},
    new Object[]{"","Join","LHS","Operator","RHS"});
    table = new JTable(dm);
    table.getTableHeader().setReorderingAllowed(false);
    table.setRowHeight(25);
    int columnWidth[] = {20,45,95,95,95};
    TableColumnModel modelCol = table.getColumnModel();
    for (int i=0;i<5;i++)
    modelCol.getColumn(i).setPreferredWidth(columnWidth);
    //modelCol.getColumn(0).setCellRenderer(new ButtonRenderer());
    //modelCol.getColumn(0).setCellEditor(new ButtonEditor(new JCheckBox()));
    modelCol.getColumn(0).setCellRenderer(new ButtonCR());
    modelCol.getColumn(0).setCellEditor(new ButtonCE(new JCheckBox()));
    modelCol.getColumn(0).setResizable(false);
    setUpJoinColumn(modelCol.getColumn(1));
    setUpLHSColumn(modelCol.getColumn(2));
    setUpOperColumn(modelCol.getColumn(3));
    setUpRHSColumn(modelCol.getColumn(4));
    JScrollPane scroll = new JScrollPane(table);
    scroll.setBounds(new Rectangle(1,1,400,133));
    mPanelScroll.add(scroll,null);
    this.getContentPane().add(mPanelCombo,null);
    this.getContentPane().add(mPanelScroll,null);
    this.getContentPane().add(mPanelButton,null);
    }//end of makeForm()
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource() == mButtonInsert)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before Insert CURRENT ROW"+currentRow);
    if(currentRow == -1)
    int rowCount = dm.getRowCount();
    //mSelectedRow = rowCount-1;
    //table.clearSelection();
    dm.insertRow(rowCount,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    else
    table.clearSelection();
    dm.insertRow(currentRow+1,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("After INSERT CURRENT ROW"+currentRow);
    if(ae.getSource() == mButtonDelete)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before DELETE CURRENT ROW"+currentRow);
    if(currentRow != -1)
    dm.removeRow(currentRow);
    table.clearSelection();
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("Selected Row"+mSelectedRow);
    else
    JOptionPane.showMessageDialog(null, "Select row first", "alert", JOptionPane.ERROR_MESSAGE);
    //System.out.println("DELETE CURRENT ROW"+currentRow);
    public void setUpJoinColumn(TableColumn joinColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("AND");
    comboBox.addItem("OR");
    comboBox.addItem("NOT");
    joinColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    joinColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = joinColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpLHSColumn(TableColumn LHSColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Participant1");
    comboBox.addItem("Participant2");
    comboBox.addItem("Variable1");
    LHSColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    LHSColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = LHSColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpOperColumn(TableColumn operColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("=");
    comboBox.addItem("!=");
    comboBox.addItem("Contains");
    operColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    operColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = operColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpRHSColumn(TableColumn rhsColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Variable1");
    comboBox.addItem("Constant1");
    comboBox.addItem("Constant2");
    rhsColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    rhsColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = rhsColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public static void main(String[] args) {
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Button as a renderer for the table cells
    class ButtonCR implements TableCellRenderer
    JButton btnSelect;
    public ButtonCR()
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    if (column != 0) return null; //meany !!!
    //System.out.println("Inside renderer########################Selected row");
    //btnSelect.setText(value.toString());
    //btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    return btnSelect;
    }//end fo ButtonCR
    //Default Editor for table
    class ButtonCE extends DefaultCellEditor implements ActionListener
    JButton btnSelect;
    JTable table;
    //Object val;
    static int selectedRow = -1;
    public ButtonCE(JCheckBox whoCares)
    super(whoCares);
    //this.row = row;
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    btnSelect.addActionListener(this);
    setClickCountToStart(1);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column)
    if (column != 0) return null; //meany !!!
    this.selectedRow = row;
    this.table = table;
    table.clearSelection();
    System.out.println("Inside getTableCellEditorComponent");
    return btnSelect;
    //public Object getCellEditorValue()
    //return val;
    public void actionPerformed(ActionEvent e)
    // Your Code Here...
    System.out.println("Inside actionPerformed");
    System.out.println("Action performed Row selected "+selectedRow);
    btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    }//end of ButtonCE

    Hi,
    All the thing you have to do is to return a boolean for the column. JTable will use a checkbox (as default) to show boolean values.

  • Problem adding columns and rows in JTable

    hi, hope somebody can help me
    i have some problems when i add columns and later i try to set number of rows in JTable, ocurr some exceptions
    my code is something like thisJTable tabla = new JTable();
    TableColumn tc = new TableColumn();
    tc.setHeaderValue("col1");
    tc.setPreferredWidth(20);
    tabla.getColumnModel().addColumn(tc);up to here everything goes well, my table shows the column, but when i add this line((DefaultTableModel)tabla.getModel()).setNumRows(1);ocurrs the next exception
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 0 >= 0....
    any ideas????

    oks, that would work when the JTable is created, but now we say that I require a method which adds a new row to the JTable a some moment of execution
    Look some of my code
    i have this in a JFrame...
    JTable tabla = new JTable();
    DefaultTableModel tm = new DefaultTableModel();
    tabla.setModel(tm);
    agrCol("Col1", 80);
    agrCol("Col2", 160);
    agrFil();
    agrFil();
    agrCol(String col, int lon) {
      tm.addColumn(col);
      tabla.getColumn(col).setPreferedWith(lon);
    agrFil() {
      tm.setRowCount(tabla.getRowCount() + 1);
    the jtable shows the 2 columns and 2 rows, but the setPreferedWith work only in the last col, i'm confused

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    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.*;
    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;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

  • Setting corect value in JTable while adding row @ run time

    HI All,
    Iam facing the following problems in Java Swing while using JTable..
    I have a JTable with 11 colums and i add row on run time..
    Since i needed the 11th column of the table to be of type CheckBox i used the follwing object in the DefaultTableModel class..
    Object[][] data =
                   {"1", "", "", "", "", "", new Double(0.0), new Integer(0), new Double(0.0), new Double(0.0),new Boolean(false) }
    When ever i wan't to delete a row i will click the Boolean Object ( which appears as a Check box ) and then delete that row.. For deleteing i am using 1 methods..
    1. By selecting the col by mouse and the click a button to delete the selected rows...
    2. By selecting the col by key board , using a Menu ShortCut key ( CTRL-F ) and then using the space key to on the value , then i use another Menu ShortCut key ( CTRL-D ) to delete all the selected rows..
    The above 2 methods work fine as for as deleting is concerned..
    But the problem starts while adding another row after deleting one or more rows..That 2 happens while the deletion had been done by the KEYBORD only..
    The problem is...
    If there is more than 1 rows and i select some rows of any order..And then delete them with the Keyboard option..and then add a rows , while adding the row @ the postion where the last row was deleted iam getting the 11th col. value ( which apears as a check box ) as selected..For example if there is 4 rows and i delete the 3rd and 4th row and then when i add rows its fine for the 3rd row and for the 4th row ( which was the last one which was slected to be deleted ) i get the option as a selected one..
    But while adding i use the above said Data object only..I then used the the
    JTablename.getValueAt(i,10); to print the value and iam geting false only..
    And more over when i try to focus in the cell in 1st row last column of the table by the setSelection method , the focus goes to the cell which appears to be enbled..
    My friends asked me to use the follwing methods before adding rows ..
    1. clearSelection()
    2. Validate()
    3. repaint()
    But the problem seems not over can anyone help....
    U can mail me to [email protected]
    Love,.
    Siva

    Yes, relatively easily, I think.
    In your end jump script set a second value in a different GPRM that identifies the last film played. This way the play all flag is set and you know which clip has just been seen.
    On resuming the play all you need to reset the play all flag to '1' and then look at the other GPRM to see which clip played last. Use a bunch of jump commands to get back in to the playback at the start of the next logical clip and it should continue through as before.
    The secret here is to clear the play all flag when showing a few clips, but use your 'resume play all' button to reset the flag and see where you were by reading the other GPRM.
    The downside here is that you could be in clip 3 when you exit the play all, but you would have to resume clip 3 from the start when you return as the 'Resume' info will get cleared if you start showing other clips in the mean time.
    Have you also considered setting up a video jukebox? You could then pick a selection of tracks to play in the order they were chosen and leave them to run through. This is a much trickier bit of scripting, but very possible!
    Stories could have made things easier, but given the set-up that you have built you can still get what you need from the scripting

  • Facing problem While deleting rows and adding rows

    Hi,
    In my form i have pass values to table rows by selecting values from Dropdown list.
    i have taken 3 hidden obj and passing the dropdown values to hidden objects and then from hidden objects to table rows.
    h1,h2,h2 are hidden obj
    EMPNO,EMPNAME, DESIGNATION are drop downlist
    i have add button with the following code
    if(form1.P1.ItemSet.EMPNO.rawValue != null){
    form1.P1.ItemSet.instanceManager.addInstance();
    form1.P1.execInitialize();
    var dynamicArray = form1.P1.resolveNode("ItemSet[" + arrayIncri + "]");
    dynamicArray .EMPNO.rawValue = form1.P1.hidden.h1.rawValue;
    dynamicArray .EMPNAME.rawValue = form1.P1.hidden.h2.rawValue;
    dynamicArray .DESIGNATION.rawValue = form1.P1.hidden.h3.rawValue;
    arrayIncri++;
    form1.P1.SF1.EmpID.rawValue = null;
    form1.P1.SF1.EmpName.rawValue = null;
    form1.P1.SF1.Designation.rawValue = null;
    My delete button code is
    _ItemSet.removeInstance(this.parent.index);
    form1.P1.execInitialize();
    My problem is adding is happening while click and deleting is happening to the perticular row but once i delete paricular row then again if i want to add new row then it is taking null values . and agian if i click add then the values are passing to the next row
    means i am getting null row if i do add funtionality after delete funtionality....
    Please help me out in this..
    Subba reddy

    Hi,
    I got the answer for this query, but when i do download and upload of the files from R/3 to GRC. Still it is not showing me the new transactions which were developed in R/3.
    it means when i try to add the transaction in a function, under search mode with respective of the r/3 system, it is not showing me the search results.
    What i did was, i run the reports /VIRSA/ZCC_DOWNLOAD_DESC & /VIRSA/ZCC_DOWNLOAD_SAPOBJ and uploaded them as below in GRC.
    Text Objects - /VIRSA/ZCC_DOWNLOAD_DESC
    permissions   -  /VIRSA/ZCC_DOWNLOAD_SAPOBJ
    For each of the download i get 2 files for each and i tried to upload both of them but no luck.
    Please suggest me, as am missing anything in this process
    SV

  • Regarding adding Rows to a Jtable programmatically

    I tried adding rows to a Jtable programmatically.
    My Jtable has the Table Model as a class that has been extended from DefaultTAbleModel.
    I tried inserting rows using addRow, and setRowCount and set RowNum methods but nothing worked..
    and I get the OutOfMemory xecption alawys and my applet hangs...

    What's in your addRow method? Are you firing the
    inserted event with fireRowsInserted?
    My snippet assumes you're storing table data in a
    vector of vectors and only want to add the row to the
    bottom of the table.
    public void addRow(Vector vector)
    data.add(vector);
    fireTableRowsInserted(data.size(),
    size(), data.size());
    addRow is a method of the DefaultTableModel class..and so I am not over riding it...
    i just use it as defaulttablemodel-object.addRow(Object[] obj);

Maybe you are looking for

  • Business process (Integration) monitoring - Solution Manager?

    Hi Experts I have a requirement here for business process monitoring at my client. The client wants to have a solution for monitoring of few key business processes for example incoming orders. The flow data flow is as follows: third party system -> A

  • Derivation Rule for Partner Function

    Dear Experts I have some questions about COPA derivation rule. I attempted to input a number for remark by using the partner function u201Ccontactu201D field in biling table (KNVP-PANRN). Itu2019s always occurred error while SD entered PGI after I co

  • Adobe form/reader  error

    Hi We are working on PCR forms in MSS and having some issues with certain forms. I am UNABLE to select any option in the PCR Adobe form's DROPDOWN LIST BOX and any Adobe form which has a dropdown list comes up with an error message "message limit exc

  • Terrible reading experience...

    I downloaded the AIR app on my Macintosh to read monographs made available by my university library. The resulting pages are one-third-filled with a single page-wide column of tiny text - text that occasionally overlaps with itself. So far as I can d

  • How to apply same editing to further audio tracks...

    Hello all, i've just made a very complicated sync between a video and audio track within an FCS project. The video was untouched and i edited the stereo audio track. Now i would like to apply the same editing to the .ac3 version of the just edited st