Table Model Listener conflict?

Before I post my problem, please let me admit that I am a fairly new beginner to Java with a problem too big for my knowledge. So please bear with my ignorance.
I have created a table with a table model that changes size at the action of a button (will create as many rows as a certain user-entered value). This seems to be working fine.
The table I am creating contains some default values, but the user will need to be able to modify these values. To read these values, I need a Table Model Listener.
However, when I add the Table Model Listener, the above feature (change the size of the table at the action of the button) stops working. Is the table listener incompatible with a dynamic-sized table? Is there a step a should add in between to let the table listener know that the table data is final and read it? Am I doing things in the wrong order?
I would appreciate any suggestions, as I am quite clueless.
Thanks
maccanena

No that shouldn't matter, the listener is doing something you don't want, the code posted works for me.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class TableTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                showUI();
    protected static void showUI() {
        Object [][] ptable = {{"p1", 2.0}};
        String[] colnamesp = { "p name:", "p value:" };
        final DefaultTableModel pTableModel = new DefaultTableModel(ptable,colnamesp);
        JTable jTable1 = new JTable(pTableModel);
        final JTextField nvarsEntry = new JTextField("1");
        JButton updateButton = new JButton("Update table");
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent updateevt) {       
                try{
                    int nvars = Integer.parseInt(nvarsEntry.getText());
                    int j;
                    int length = pTableModel.getRowCount();
                    if (length<nvars) {
                        for (j=length;j<nvars;j++) {
                            pTableModel.addRow(new Object[] {"p"+String.valueOf(j+1), 2.0});                                         
                    else if (length>nvars) {
                        for (j=nvars;j<(length+1);j++) {
                            pTableModel.removeRow(nvars);
                } catch (Exception e) {                 
        jTable1.getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent evtable1) {
                int row = evtable1.getFirstRow();
                int column = evtable1.getColumn();
                // Do something with the data...
        JFrame frame = new JFrame();
        Container contentPane = frame.getContentPane();
        contentPane.add(updateButton, BorderLayout.PAGE_START);
        contentPane.add(nvarsEntry, BorderLayout.PAGE_END);
        contentPane.add(new JScrollPane(jTable1), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
}

Similar Messages

  • Problem with Table Model Listener

    I hava a JTable with three columns and dynamic number of rows. The first column has a text. Second column has check box and each third column has three radio buttons. I am using the table model listener to fetch the row and column which the user clicked. here is the code
    public void tableChanged(TableModelEvent e)
    row = e.getFirstRow();
    column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object value = model.getValueAt(row, column);
    System.err.println("Value: "<em>value.toString()</em>" Row: "<em>row</em>" Column: "+column);
    attendanceModel.setHolidays(row, value.toString());
    }Here is the problem
    {color:#ff0000}Case 1{color}: When I click the first radio button in first row and third column it works and the output of print statement is
    *{color:#993300}Value:0 Row:0 Column:2{color}*
    {color:#ff0000}Case 2{color}: Next I clicked the first radio button in second row and third column the method is not called nothing is printed
    {color:#ff0000}Case 3{color}: Now I clicked the first radio button in third row and thrid column, the method is called and the output of print statement is
    {color:#993300}*Value:0 Row:1 Column:2*{color} ; but the actual value of row should be 2*. Here it is showing the row and column of the previously selected item.
    But in {color:#ff0000}case 2{color} instead of first radio button if I selected the second radio button the print statement will print the correct value i.e
    {color:#993300}*Value:1 Row:1 Column:2*{color}
    ie If I select different radio button in each row the print statement shows the correct value. But if in each row the same radio button is selected its not working properly. For first row it prints properly. If same radio button is selected in second row the method is not called. But from next row onwards the row value is showing the previously selected row as in {color:#ff0000}case 3{color}.
    But for the checkboxes in column 2 the same is working properly. Each column has only one check box. So when I select the check box in each row the row and column values are getting changed accordingly.
    Could some one help please?
    Thanks,
    Zach.

    To get better help sooner, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html] that demonstrates the incorrect behaviour.
    db

  • How to use JTable model listener???

    Anyone got idea , how to use table model listener. Can explain in simple example with code?? how to pass back to resultset ??

    Well, your pretty good at asking questions, but not very good at thanking people for the help given to you so I don't think I'll waste too much time helping this time.
    A TableModelListener notifies you when the contents of a cell are changed. So simply take the data from the cell and update your ResultSet. You question is so general I don't know how you expect any more advice than that.

  • Table event listener for both columns and rows

    My table listener only gives me the printed values when I click on different rows and not when I click on different columns. Do I need 2 listeners (one inside the other one) to get a change recorded each time I click on a cell in the table? Here is the listener code:
          ListSelectionModel rowSM1 = jTable1.getSelectionModel();
          rowSM1.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
              System.out.println("I am here");
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              if (e.getValueIsAdjusting()) {
                return;
              if (lsm.isSelectionEmpty()) {
                //no rows are selected
              else {
                selectedSiteRow = new Integer(lsm.getMinSelectionIndex() + 1).toString();
                System.out.println("selectedSiteRow = " + selectedSiteRow);
                SetupNum = selectedSiteRow; // row that the user selected
                ObjectNum = "1";
                objnum = "1";
                dataModels.remove("O"); // remove the object tables from the dataModels hashtable
                dataModels.remove("P"); // remove the object tables from the dataModels hashtable
                for (int i = 0; i < wholefile.size(); i++) {
                  setupnum = selectedSiteRow;
                  if (wholefile.elementAt(i).toString().charAt(0) == 'O') {
                    processLine(wholefile.elementAt(i).toString(), columnNamesO);
                    String keyO = "O";
                    DefaultTableModel modelO = (DefaultTableModel)dataModels.get(keyO);
                    jTable2.setModel(modelO); // change the table to the new table model
                  if (wholefile.elementAt(i).toString().charAt(0) == 'P') {
                    processLine(wholefile.elementAt(i).toString(), columnNamesP);
                    String keyP = "P";
                    DefaultTableModel modelP = (DefaultTableModel)dataModels.get(keyP);
                    jTable3.setModel(modelP); // change the table to the new table model
        );The words "I am here" only appear when I click on rows and not when I click on columns of that same row. Anyone know why?
    Also, each time I click on a row, "I am here" appears 2 times. I know I read that someone else had that problem. I will try to find the solution to that one in the forum.
    Thanks.
    Allyson

    I found out how to get the column, but I can't seem to get them together. Here is the listener for the column:
          ListSelectionModel colSM1 = jTable1.getColumnModel().getSelectionModel();
          colSM1.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
              if (e.getValueIsAdjusting()) {
                return;
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              if (lsm.isSelectionEmpty()) {
                //no columns are selected
              else {
                SelectedC = lsm.getMinSelectionIndex();
          });These are 2 different listeners and I really want to find out what row,column has changed. Is there any way to combine these somehow? Thanks.
    Allyson

  • Using Table Model as a Grid?

    Would it be possible to add JButtons(or JPanels) to create cells in a Table Model implementation? How would I go about this? Would I then be able to listen for events from these JButtons using the methods native to table model such as getValueAt(int row, int col) etc.
    What I am trying to do is to implement a grid of 10X10 cells for a battleship game so that the user can click on cells on the grid and that this will trigger an event specifying to user whether it was a hit or miss etc. and change the color of cell (JButton) based on hit/miss etc.
    Any help would be appreciated.
    Thanks.

    Well you need:
    1) a custom cell renderer class that is able to manage the change of background and the contents of the cell by itself
    2) a custom cell event listener that allows you to get and process the messages.
    You can find a full-featured example at the address: http://www.java2s.com/Code/Java/Swing-JFC/TableEditorEditableColorColumn.htm

  • Use ComboBox TableCellEditor  - values are not saved to the table model

    Hi,
    I got a combobox cell editor that uses to edit one of the columns.
    And i got an ok button that uses to collect the data from the table and save it to the db.
    In case i started editing of a cell and the editor is still displayed- if i will click on the button the data that will be colected from the table model will not contained the updated value in the cell editor.
    In this case the user think his changes were saved but the last updated field is not updated.
    Is this a bug i got in the cell editor or this is the normal behaviour?
    Can it be fixed? (So that if the cell is in the middle of editing the value that will be saved is the last value that was selected).
    public class PriorityCellEditor extends StandardComboBox implements TableCellEditor {
        private boolean isEditMode=false;
         * A list of eventlisteners to call when an event is fired
        private EventListenerList listenerList = new EventListenerList();
         * the table model
        public StbAreaClusterPriorityCellEditor(boolean isEditMode) {
            super(StbAreaMapper.clustersPriorities);
            setEditMode(isEditMode);
            setEditable(false);
            this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            setAlignmentX(Component.LEFT_ALIGNMENT);
        public boolean isEditMode() {
            return isEditMode;
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setEnabled(editMode);
        public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelecte, int row, int column) {
            int selectedIndex;
            if (isSelecte) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            if(value instanceof String){
                selectedIndex=StbAreaMapper.mapGuiPriorityDescToGuiCode((String)value);
                setSelectedIndex(selectedIndex);
            return this;
        public void cancelCellEditing() {
            fireEditingCanceled();
        public Object getCellEditorValue() {
            return getSelectedItem();
        public boolean isCellEditable(EventObject anEvent) {
            return isEditMode;
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        public boolean stopCellEditing() {
            fireEditingStopped();
            return true;
         * Adds a new cellEditorListener to this cellEditor
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);
         * Removes a cellEditorListener from this cellEditor
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingStopped(
                            new ChangeEvent(this));
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this));
    }

    Try this
    yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

  • Adding data to a table model at run time

    hiii
    i want to add data to the table model at runtime.
    i have used TableModel.My code looks like this
    public class CaptureTableModel extends AbstractTableModel {
         private String[] columnNames = { "No", "Source", "Destination", "Protocol",
                   "Flags" };
         private TCPPacket tcpPacket;
         private List data;
         private static int counter = 0;
         private int columnCount = columnNames.length;
         public CaptureTableModel(){}
         public CaptureTableModel(TCPPacket tcp) {
              try{
              tcpPacket=tcp;
              counter++;
              byte[] tcpdata = tcpPacket.getData();
              String srcHost = tcpPacket.getSourceAddress();
              String dstHost = tcpPacket.getDestinationAddress();
              String tcpPacketData = new String(tcpdata, "ISO-8859-1");
              if (tcpPacketData == null)
                   tcpPacketData = "";
              int protocol = tcpPacket.getProtocol();
              String proto = null;
              if (protocol == 6)
                   proto = "TCP";
              long sequenceNumber = tcpPacket.getSequenceNumber();
              data = new ArrayList();
              String[] info = {
                        Integer.toString(counter),
                        srcHost,
                        dstHost,
                        proto,
                        "[ACK " + tcpPacket.isAck() + " ; FIN " + tcpPacket.isFin()
                                  + " ; PUSH " + tcpPacket.isPsh() + " ; RESET "
                                  + tcpPacket.isRst() + " ; SYN " + tcpPacket.isSyn()
                                  + " ; URGENT " + tcpPacket.isUrg() };
              data.add(info);
         } catch (Exception e) {
              e.printStackTrace();//return null;
         public int getRowCount() {
              return counter;
         public int getColumnCount() {
              return columnCount;
         public String getColumnName(int column) {
              return columnNames[column];
         public Object getValueAt(int rowIndex, int columnIndex) {
              System.out.println("the value in getValueAt"+((Object[])data.get(rowIndex))[columnIndex]);
              return ((Object[])data.get(columnIndex))[rowIndex];
              //return null;
    the method getValueAt is not bieng called..where am i going wrong.
    can anyone help me??

    Use the "code" formatting tags when posting code so the code retains its original formatting.
    i want to add data to the table model at runtime.Use the DefaultTableModel it supports dynamic methods like addRow(...), removeRow().

  • Copyig Data from a TABLE MODEL (TABLE) TO A FILE

    Hi guys,
    I wont to copy data from a Default Table Model to a File can someone write a pease of code that will do that for me.
    DefaultTableModel model = new DefaultTableModel();
    JTable table;
    public basic()
              super();
                  model.addColumn("Full Name");
                  model.addColumn("House No");
                  model.addColumn("Address");
                  model.addColumn("Town/County");
                  model.addColumn("Postcode");
                  model.addColumn("Telephone Number");
                  model.addColumn("Email Address");             
                  String[] socrates = { "Example", "33", "York RD", "Poole", "BH18 9RE", "01202776655", "[email protected]" };
                  model.addRow(socrates);
              /**This is the main setup for the Address Book
              *This has the main settings for the size, title
              *And main features of the Address book.
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(new Dimension(800, 600));
              this.setTitle("Large Print Address Book");
              this.setLayout(new FlowLayout ());
              //Main Application Parts
              JLabel welcome = new JLabel("Welcome to Thomas's Address Book v2.0.1");
              welcome.setFont(arial20);
              this.add(welcome);
              //Menu Bar
              JMenuBar mb = new JMenuBar();
              this.setJMenuBar(mb);
              //Table
              table = new JTable(model);
              this.add(table);
              JMenu fm = new JMenu("File");
              fm.setFont(arial20);
              mb.add(fm);
              //Menu Items          
              JMenuItem Add = new JMenuItem("Add Record");
              Add.setFont(arial20);
              Add.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        addw a = new addw();                    
              fm.add(Add);
              //Import from a file
              JMenuItem inp = new JMenuItem("Import Records");
              inp.setFont(arial20);
              inp.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        //Opens Import Window.
                        inportw i = new inportw();                    
              fm.add(inp);
              JMenuItem quit = new JMenuItem("Exit");
              quit.setFont(arial20);
              fm.add(quit);
              quit.addActionListener(this);
    class inportw extends JFrame
              //*Add Window Properties and Settings
              public inportw ()
                   this.setSize(new Dimension(400, 150));
                   this.setTitle("Inport Records");
                   this.setLayout(new FlowLayout ());
                   this.setVisible(true);
                   //Nmae
                   JLabel error_note = new JLabel("Error Here - Need to make table final!?");
                   error_note.setFont(arial20);
                   this.add(error_note);
                   //Add Button
                   JButton binport = new JButton("Inport");
                   binport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             ArrayList data = new ArrayList();          
                   this.add(binport);
         public void actionPerformed(ActionEvent e)
              System.out.println("Application Exit");
              System.exit(0);
         public static void main(String[] args)
              basic b = new basic();
              The information from the atable needs to go into a .txt file with each row on a new line. It also needs to be in the inport/export window that is in a class on its own when someone clicks export.
    A complete peace of code would be helpfull that would do this for me. Thankyou guys.

    Rite then,
    In answer to both post yes i have done my own homework if thats what you wont to call it.
    And to the second post yes i have put in a File to export to. the code has not be pasted on my origanal post.
    //Export Button - Export Window
                   JButton bexport = new JButton("Export (BUAB)");
                   bexport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             System.out.println("Export Pressed ");
                             try
                                 FileWriter file = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write("AddressBook data File");
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                   this.add(bexport);This is the export button,
    I think the code for the table model should be something like this:
    I wont to do something like this
    model.getModel().getValueAt(0, 0);
    Arrylist data = new arrylist();
    try
                                 FileWriter ffile = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write(data);
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                                 }          Im not 100% sure how to get the information from the model into the arrylist, though a loop.
    If there is a section of a webpage that may help could someone please post it for me.
    Unfortunatly for me Im visualy impaired and find some of this hard. I learn though looking at examples and creating my own programs that do something similar.
    If no one wonts to help then that fine with me !

  • JTable column headers not displaying using custom table model

    Hi,
    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
            etc
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
            fields=f;
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.
    Cheers,
    garsher

  • Transfer Data from a JTable to the table model

    Hi
    I' looking for a simple method to transfer the last user input in a table to the table model.
    For example:
    In a Dialog the user insert in a JTable a few values and leaves with OK. But the last input is not saved in the model. It is just saved after selecting a new field in the JTable before leaving the Dialog.
    Is there a call to transfer all input to the model?
    Thanks
    Guido

    class MyJTable extends JTable (
    public boolean validateInput() {
    if(isEditing()) {
    return cellEditor.stopCellEditing();
    return true;
    Call this method whenever you want the input value to be stored in the table model. The return value can be false if the input isn't valid, this will depend on the cell editor.
    The idea is:
    Ask if the table has an editor activated. (isEditing())
    If so, request the editor to store the value in the model.
    I haven't prouved the code, sorry, but I hope you get the idea and helps.

  • A question about table model

    I created a table model and use JTable to display content of a database's table with that model.
    The problem is: when I update a data to data1 in a cell (first column) and hightlight another cell (second column), all cells of first column change content to data1. What 's the problem with my table model?
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.table.AbstractTableModel;
    public class CommonTableModel extends AbstractTableModel {
    String[] columnNames;
    Vector          rows, newRow;
    ResultSetMetaData metaData;
    private boolean editable;
    public CommonTableModel(ResultSet rs, boolean editable) {
    this.editable = editable;
    try {
    metaData = rs.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnName(column+1);
    rows = new Vector();
    newRow = new Vector();
    while (rs.next()) {
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(rs.getObject(i));
    rows.addElement(newRow);
    } catch (SQLException ex) { System.err.println(ex);}
    public int getColumnCount() { return columnNames.length; }
    public int getRowCount() { return rows.size();}
    public String getColumnName(int column) { return columnNames[column];}
    public Object getValueAt(int row, int column) {
         newRow = (Vector)rows.elementAt(row);
         return newRow.elementAt(column);
    public Class getColumnClass(int column) {
         return getValueAt(0, column).getClass();
    public boolean isCellEditable(int row, int column) {
         if (column == 0) { return false; }
         return editable;
    public void setValueAt(Object value, int row, int column) {
         newRow = (Vector)(rows.elementAt(row));
         newRow.setElementAt(value, column);
         fireTableCellUpdated(row, column);
    }

    Try this :
    rows = new Vector();
    //newRow = new Vector();
    while (rs.next()) {
        newRow = new Vector(); // it must be here
        for (int i = 1; i <= getColumnCount(); i++) {
            newRow.addElement(rs.getObject(i));
        rows.addElement(newRow);
    }Denis

  • How can I add an adornment to a table model?

    Hi
    - Is it possible to add an adornment to a table model?
    -  If yes how can I do that? Interface? Sample?
    Thanks for any hint
    Hans

    Hi,
    How can I add an attribute to a node of a DOM
    Document?
    I want to add attribute Maximum="6" for all Grade node
    as <Grade Maximum="6">.
    Grade is a third level node in my document.
    ThanksGet the father of "Grade" elements as an element. Then get all elements named "Grade", and for each one set attribute "Maximum" with value "6". If you read api documentation you will know which methods to use.
    But for helping you in getting the "Grade" parent.
    1) get the root element of the Dom Doc
    2)get the father of the "Grade" father: getElementsBytagName("his name") -> it will return a Node List get the first element casting as Element if there's only one, or elese if not case
    3)the same method in 2 get the "Grade" father
    4)getElementByTagName("Grade") over the "Grade" father -> for each "grade" element on nodelist do whatever you need
    i hope u understood...

  • How to Add and delete a row while using Abstract Table Model

    Hi,
    I need to do the following functionalities in JTable.I've done tht but a small problem.
    1. Adding a row (Using addRow() method from DefaultTableModel).
    2. Deleting a row(Using setRowCount() method from Default Table Model).
    3. Sorting the table based on the selection of column(Using TableSorter which is using AbstracTableModel).
    As the sorting is mandatory i've to change my model to Abtract Table Model
    The problem is this Abstract Table Model doesn't have any methods to Add a row or deleting a row (setRowCount()).If anybody has written any utility method for this using Abstract Table Model help me.

    Using TableSorter which is using AbstracTableModel).If your talking about the TableSorter class from the Swing tutorial, then you create the TableSorter class by passing it a TableModel. There is no reason you can't use the DefaltTableModel.
    I changed the code in TableSorterDemo as follows:
            String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new BigDecimal(1), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new BigDecimal(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new BigDecimal(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new BigDecimal(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new BigDecimal(10), new Boolean(false)}
              DefaultTableModel model = new DefaultTableModel(data, columnNames)
                   public Class getColumnClass(int c)
                        return getValueAt(0, c).getClass();
            TableSorter sorter = new TableSorter(model);
    //        TableSorter sorter = new TableSorter(new MyTableModel()); //ADDED THIS

  • Problem of custom table model

    Hi,
    i m leaning JTable recently, following is an experimental code which i wrote, it has a custom table model and custom tablecellrenderer, the custom tablecellrender determine the column of # of Years greater or equal than 5 should display color green, less than 5 should display color red, it works well, however, the custom table model should be smart enough to know that the # of Years column contains numbers (which should generally be right aligned and have a particular format), it also should know that the Vegetarian column contains boolean values, which can be represented by check boxes, but it didn't, i don't know why, i have implement a getColumnClass method,
    but it seems not work, have i make any mistakes? Any idea? Thanks
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.UIManager;
    import java.awt.Color;
    import java.util.Vector;
    public class CellRenderTestVector extends JFrame {
         protected JTable table;
         protected int width = 100;
         protected MyCustomTableModel model;
         public CellRenderTestVector() {
              JPanel pan0 = new JPanel(new BorderLayout());
              Container contentPane = getContentPane();
              pan0.setPreferredSize(new Dimension(500,200));
              model = new MyCustomTableModel();
              table = new JTable();
              table.setAutoCreateColumnsFromModel(false);
              table.setModel(model);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            TableColumn column = null;
              for (int i = 0; i < model.getColumnCount(); i++) {
                   DefaultTableCellRenderer renderer = new
                     ColoredTableCellRenderer();
                   column = new TableColumn(i,
                              width, renderer, null);
                              table.addColumn(column);
              TableColumn t_column = table.getColumnModel().getColumn(2);
              System.out.println(table.getColumnModel());
              JScrollPane scrollPane = new JScrollPane(table);
              pan0.add(scrollPane, BorderLayout.CENTER);
              contentPane.add(pan0);
                public class ColoredTableCellRenderer extends DefaultTableCellRenderer {
              public void setValue(Object value) {
                   Color  m_color;
                   Color GREEN = new Color(0, 128, 0);
                   Color RED = Color.red;
                   if (value instanceof Integer) {
                        Integer m_data = (Integer)value;
                        m_color = m_data.intValue() >= 5 ? GREEN : RED;
                                           setForeground(m_color);
                               setText(m_data.toString());
                   else {
                        super.setValue(value);
         public class Columndata {
              protected String m_title;
              public Columndata(String title) {
                   m_title = title;
         public class Rowdata {
              protected String fname;
              protected String lname;
              protected String sport_type;
              protected Integer no_year;
              protected Boolean vegetarian;
              public Rowdata(String fn, String ln,
                        String sp, int ny, boolean vg) {
                   fname = fn;
                   lname = ln;
                   sport_type = sp;
                   no_year = new Integer(ny);
                   vegetarian = new Boolean(vg);
         public class MyCustomTableModel extends AbstractTableModel {
              protected final Columndata m_column[] =
                        {new Columndata("First Name"),
                         new Columndata("Last Name"),
                         new Columndata("Sport"),
                         new Columndata("# of Years"),
                         new Columndata("Vegetarian")
              protected Vector m_vector;
              public MyCustomTableModel() {
                   m_vector = new Vector();
                   setDefaultData();
              public void setDefaultData() {
                   m_vector.removeAllElements();
                   m_vector.addElement(new Rowdata("Mary", "Campione",
                                                           "Snowboarding", 5, false));
                   m_vector.addElement(new Rowdata("Alison", "Huml",
                                                           "Rowing",3,true));
                   m_vector.addElement(new Rowdata("Kathy", "Walrath",
                                                           "Knitting",2, false));
                   m_vector.addElement(new Rowdata("Sharon", "Zakhour",
                                                           "Speed reading",20,true));
                   m_vector.addElement(new Rowdata("Philip", "Milne",
                                                           "Pool",10,false));
              public int getColumnCount() {
                   return m_column.length;
              public int getRowCount() {
                   return m_vector==null ? 0 : m_vector.size();
              public String getColumnName(int col) {
                   return m_column[col].m_title;
              public Object getValueAt(int nRow, int nCol) {
                   if (nRow < 0 || nRow>=getRowCount()) return "";
                   Rowdata row = (Rowdata)m_vector.elementAt(nRow);
                   switch (nCol) {
                   case 0: return row.fname;
                   case 1: return row.lname;
                   case 2: return row.sport_type;
                   case 3: return row.no_year;
                   case 4: return row.vegetarian;
                   return "";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
         public static void createAndShowGUI() {
              try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch (Exception evt) {}
                   JFrame f = new CellRenderTestVector();
                   f.setTitle("TableTest");
                   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   f.pack();
                 f.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    You need to write your custom TableCellRenderes/Editors for each type. And don't forget to register your custom renderes via myTable.setDefaultRendere().

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

Maybe you are looking for