Jtable IntegerEditor

I have downloaded a code for table cell editing from sun site. The code is as follows:
* NewClass.java
* Created on July 30, 2008, 11:35 AM
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package tableapplication;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.AbstractAction;
import javax.swing.DefaultCellEditor;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
public class IntegerEditor extends DefaultCellEditor {
   JFormattedTextField ftf;
   NumberFormat integerFormat;
   private Integer minimum, maximum;
   private boolean DEBUG = false;
   public IntegerEditor(int min, int max) {
       super(new JFormattedTextField());
       ftf = (JFormattedTextField)getComponent();
       minimum = new Integer(min);
       maximum = new Integer(max);
       //Set up the editor for the integer cells.
       integerFormat = NumberFormat.getIntegerInstance();
       NumberFormatter intFormatter = new NumberFormatter(integerFormat);
       intFormatter.setFormat(integerFormat);
       intFormatter.setMinimum(minimum);
       intFormatter.setMaximum(maximum);
       ftf.setFormatterFactory(
               new DefaultFormatterFactory(intFormatter));
       ftf.setValue(minimum);
       ftf.setHorizontalAlignment(JTextField.TRAILING);
       ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
       //React when the user presses Enter while the editor is
       //active.  (Tab is handled as specified by
       //JFormattedTextField's focusLostBehavior property.)
       ftf.getInputMap().put(KeyStroke.getKeyStroke(
                                       KeyEvent.VK_ENTER, 0),
                                       "check");
       ftf.getActionMap().put("check", new AbstractAction() {
           public void actionPerformed(ActionEvent e) {
      if (!ftf.isEditValid()) { //The text is invalid.
                   if (userSaysRevert()) { //reverted
              ftf.postActionEvent(); //inform the editor
               } else try {              //The text is valid,
                   ftf.commitEdit();     //so use it.
                   ftf.postActionEvent(); //stop editing
               } catch (java.text.ParseException exc) { }
   //Override to invoke setValue on the formatted text field.
   public Component getTableCellEditorComponent(JTable table,
           Object value, boolean isSelected,
           int row, int column) {
       JFormattedTextField ftf =
           (JFormattedTextField)super.getTableCellEditorComponent(
               table, value, isSelected, row, column);
       ftf.setValue(value);
       return ftf;
   //Override to ensure that the value remains an Integer.
   public Object getCellEditorValue() {
       JFormattedTextField ftf = (JFormattedTextField)getComponent();
       Object o = ftf.getValue();
       if (o instanceof Integer) {
           return o;
       } else if (o instanceof Number) {
           return new Integer(((Number)o).intValue());
       } else {
           if (DEBUG) {
               System.out.println("getCellEditorValue: o isn't a Number");
           try {
               return integerFormat.parseObject(o.toString());
           } catch (ParseException exc) {
               System.err.println("getCellEditorValue: can't parse o: " + o);
               return null;
   //Override to check whether the edit is valid,
   //setting the value if it is and complaining if
   //it isn't.  If it's OK for the editor to go
   //away, we need to invoke the superclass's version
   //of this method so that everything gets cleaned up.
   public boolean stopCellEditing() {
       JFormattedTextField ftf = (JFormattedTextField)getComponent();
       if (ftf.isEditValid()) {
           try {
               ftf.commitEdit();
           } catch (java.text.ParseException exc) { }
       } else { //text is invalid
           if (!userSaysRevert()) { //user wants to edit
           return false; //don't let the editor go away
       return super.stopCellEditing();
    * Lets the user know that the text they entered is
    * bad. Returns true if the user elects to revert to
    * the last good value.  Otherwise, returns false,
    * indicating that the user wants to continue editing.
   protected boolean userSaysRevert() {
       Toolkit.getDefaultToolkit().beep();
       ftf.selectAll();
       Object[] options = {"Edit",
                           "Revert"};
       int answer = JOptionPane.showOptionDialog(
           SwingUtilities.getWindowAncestor(ftf),
           "The value must be an integer between "
           + minimum + " and "
           + maximum + ".\n"
           + "You can either continue editing "
           + "or revert to the last valid value.",
           "Invalid Text Entered",
           JOptionPane.YES_NO_OPTION,
           JOptionPane.ERROR_MESSAGE,
           null,
           options,
           options[1]);
       if (answer == 1) { //Revert!
           ftf.setValue(ftf.getValue());
       return true;
   return false;
}The problem is that when I edit a cell having Integer value and enter a text eg "s10" and press enter it shows Revert Edit dialog but when I enter eg "10s" and press enter it doesn't show Revert Edit Dialog.
Please help me.

If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

Similar Messages

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    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 < 1) {
    return false;
    } else {
    return true;
    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("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

  • How to display time duration (NOT dates) with an input mask in a JTable?

    Background: I am trying to display in a JTable, in two columns, the start position and time duration of an audio clip.
    They are stored as type float internally eg. startPosition = 72.7 seconds.
    However I wish to display on screen in the table in HH:mm:ss:S format. eg. 00:01:12:7. The user can edit the cell and input values to update the internal member fields.
    Problem: I am finding it very difficult to implement this - what with the interactions of MaskFormatter, DefaultCellEditor etc.
    Also using SimpleDateFormat and DateFormatter does not work as they insist on displaying the day, month, year also in the table cell.
    Taking the Swing Tutorial TableFTFEditDemo example as a template,
    (http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#TableFTFEditDemo)
    does anyone know how to do this?
    I can post my (buggy) modifications to the example code - if it would help.
    Appreciate any help.
    thanks,
    Anil

    Here are my modifications to the TableFTFEditDemo example. If you run it, you get an exception
    like java.lang.NumberFormatException: For input string: "18:00:03.500"
    The two modified classes are taken from the Tutorial and are listed below:
    =================
    * IntegerEditor is a 1.4 class used by TableFTFEditDemo.java.
    import javax.swing.AbstractAction;
    import javax.swing.BorderFactory;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JFormattedTextField;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    import javax.swing.SwingUtilities;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Toolkit;
    import java.text.DateFormat;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import javax.swing.text.DateFormatter;
    import javax.swing.text.DefaultFormatterFactory;
    import javax.swing.text.MaskFormatter;
    import javax.swing.text.NumberFormatter;
    class TimeRenderer {
         float seconds;
         TimeRenderer(String str) {
              int hSec = Integer.parseInt(str.substring(0,2)) * 60 * 60;
              int mSec = Integer.parseInt(str.substring(2,4)) * 60;
              int sSec = Integer.parseInt(str.substring(4,6));
              float tSec = Integer.parseInt(str.substring(6,7))/10.0F;
              seconds = hSec + mSec + sSec + tSec;
    * Implements a cell editor that uses a formatted text field to edit Integer
    * values.
    public class IntegerEditor extends DefaultCellEditor {
         JFormattedTextField ftf;
         static Date zeroTime = new Date(0L);
         private boolean DEBUG = true;
         SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.S");
         MaskFormatter maskFo = new MaskFormatter("##:##:##.#");
         protected MaskFormatter createFormatter(String s) {
              MaskFormatter formatter = null;
              try {
                   formatter = new MaskFormatter(s);
              } catch (java.text.ParseException exc) {
                   System.err.println("formatter is bad: " + exc.getMessage());
                   System.exit(-1);
              return formatter;
         public IntegerEditor(int min, int max) throws ParseException {
              super(new JFormattedTextField(new MaskFormatter("##:##:##.#")));
              ftf = (JFormattedTextField) getComponent();
              // Set up the editor for the cells.
              ftf.setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(sdf)));
              ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);
              // React when the user presses Enter while the editor is
              // active. (Tab is handled as specified by
              // JFormattedTextField's focusLostBehavior property.)
              ftf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check");
              ftf.getActionMap().put("check", new AbstractAction() {
                   public void actionPerformed(ActionEvent e) {
                        if (!ftf.isEditValid()) { // The text is invalid.
                             ftf.setBorder(BorderFactory.createLineBorder(Color.RED));
                             ftf.setBackground(Color.PINK);
                             ftf.postActionEvent(); // inform the editor
                        } else
                             try { // The text is valid,
                                  ftf.commitEdit(); // so use it.
                                  ftf.postActionEvent(); // stop editing
                             } catch (java.text.ParseException exc) {
         // Override to invoke setValue on the formatted text field.
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              JFormattedTextField ftf = (JFormattedTextField) super
                        .getTableCellEditorComponent(table, value, isSelected, row, column);
              System.out.println("value:" + value);
    //          long milliseconds =(long) (Float.parseFloat(value.toString()) * 1000);
              long milliseconds =(long) (((Float) value).floatValue() * 1000);
              Date dt = new Date(milliseconds);
              ftf.setValue(dt);
              return ftf;
         // Override to ensure that the value remains an Integer.
         public Object getCellEditorValue() {
              JFormattedTextField ftf = (JFormattedTextField) getComponent();
              Object o = ftf.getValue();
              try {               
                   Calendar cal = Calendar.getInstance();
                   cal.setTime((Date)o);
                   float seconds = cal.getTimeInMillis()/1000.0F;
                   return sdf.format(o);
                   //return new Float(seconds);
              } catch (Exception exc) {
                   System.err.println("getCellEditorValue: can't parse o: " + o);
                   exc.printStackTrace();
                   return null;
         // Override to check whether the edit is valid,
         // setting the value if it is and complaining if
         // it isn't. If it's OK for the editor to go
         // away, we need to invoke the superclass's version
         // of this method so that everything gets cleaned up.
         public boolean stopCellEditing() {
              JFormattedTextField ftf = (JFormattedTextField) getComponent();
              if (ftf.isEditValid()) {
                   try {
                        ftf.commitEdit();
                   } catch (java.text.ParseException exc) {
              } else { // text is invalid
                   ftf.setBorder(BorderFactory.createLineBorder(Color.RED));
                   ftf.setBackground(Color.PINK);
                   return false; // don't let the editor go away
              return super.stopCellEditing();
    //=====================================================
    * TableFTFEditDemo.java is a 1.4 application that requires one other file:
    *   IntegerEditor.java
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.text.ParseException;
    * This is exactly like TableDemo, except that it uses a
    * custom cell editor to validate integer input.
    public class TableFTFEditDemo extends JPanel {
        private boolean DEBUG = false;
        public TableFTFEditDemo() throws ParseException {
            super(new GridLayout(1,0));
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Set up stricter input validation for the integer column.
         //   table.setDefaultEditor(Float.class,
           //                        new IntegerEditor(0, 100));
         //If we didn't want this editor to be used for other
         //Integer columns, we'd do this:
         table.getColumnModel().getColumn(3).setCellEditor(
              new IntegerEditor(0, 100));
            //Add the scroll pane to this panel.
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            private Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Float(5.7), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Float(3.5), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Float(2.9), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Float(20.8), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Float(10.5), new Boolean(false)}
            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) {
                 Object obj = getValueAt(0, c);
                 System.out.println("getColumnClass.obj:" + obj);
                return obj.getClass();
            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;
            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.
         * @throws ParseException
        private static void createAndShowGUI() throws ParseException {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableFTFEditDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableFTFEditDemo newContentPane = new TableFTFEditDemo();
            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() {
                    try {
                             createAndShowGUI();
                        } catch (ParseException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
    }

  • SINGLE_INTERVAL_SELECTION in Jtable

    I have a Jtable. One column data is a Boolean. If I set
    my_table.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
    then everything is OK. The box will be checked or unchecked if I click on it. But when I change it to SINGLE_INTERVAL_SELECTION, it does not work as I want. I am able to select one contiguous range of indices at a time(with shift key on). But not all the selected check boxes changed the status. Only the first one and the last one. The behavior is just like SINGLE_SELECTION. I think it does not listen to the shift key.
    Can anyone help me on this? Thanks a lot.

    I tried your version of valueChanged.
    1. int firstIndex = e.getFirstIndex(); int lastIndex = e.getLastIndex();
    Does not work!
    2. Include the single row selection in the valueChanged does not make the problem go away.
    3. I'd like the Boolean cell value toggle if user clicks on the cell. Including the single row selection in the valueChanged, sometimes(not always) will need click twice. If I do not handle it, then it acts just what I want.
    I have modified a sample code provided by SUN. Please run it and see the results.
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    // Add by Anna
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    * I implemented the ListSelectionListener, anna
    public class MyTableDialogEditDemo extends JFrame
                        implements ListSelectionListener
    private boolean DEBUG = false;
         JTable table = null;
         MyTableModel myModel = null;
    public MyTableDialogEditDemo() {
    super("MyTableDialogEditDemo");
    myModel = new MyTableModel();
    table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener( this );
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
              setSize( 700, 300 );
              setVisible(true);
         public void valueChanged(ListSelectionEvent e)
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) return;
              //int firstIndex = e.getFirstIndex(); // does not work!
              //int lastIndex = e.getLastIndex();          // does not work!
              int firstIndex = lsm.getMinSelectionIndex();
              int lastIndex = lsm.getMaxSelectionIndex();
              System.out.println( "firstIndex=" + firstIndex + ", lastIndex=" + lastIndex);
              if ( lastIndex == firstIndex )      {
                   Boolean b = (Boolean)myModel.getValueAt( firstIndex, 4 );
                   if ( b.booleanValue() )
                        myModel.setValueAt( Boolean.FALSE, firstIndex, 4 );
                   else myModel.setValueAt( Boolean.TRUE, firstIndex, 4 );
                   return;
              for ( int i=firstIndex; i<=lastIndex; i++ )     myModel.setValueAt( Boolean.TRUE, i, 4 );
              /* My original code.
              int[] indices = table.getSelectedRows();
              int ct = indices.length;
              int r1 = indices[0];
              int r2 = r1 + ct;
              if ( ct == 1 )      return;                    
              for ( int i=r1; i<r2; i++ )     myModel.setValueAt( Boolean.TRUE, i, 4 );
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setBackground((Color)color);
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(Color.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(Color.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentColor = colorChooser.getColor();
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    button.setBackground(colorEditor.currentColor);
    colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    Color currentColor = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentColor;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentColor = (Color)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary", new Color(153, 0, 153),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new Color(51, 51, 153),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new Color(51, 102, 51),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", Color.blue,
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Anna", Color.gray,
    "PingPong", new Integer(20), new Boolean(false)},
    {"David", Color.red,
    "swim", new Integer(20), new Boolean(false)},
    {"Philip", Color.pink,
    "Pool", new Integer(7), new Boolean(false)}
    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 < 4) {
    return false;
    } else {
    return true;
    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);
    public static void main(String[] args) {
    MyTableDialogEditDemo frame = new MyTableDialogEditDemo();

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • JTable - Can I change the color of the text on a row by row basis?

    Hi All,
    I'm redoing a bit of old uni coursework (to model a stockmarket, stock ticker server & stock ticker application) to brush up my Java skills (esp Swing and Event Handling) and am programming the UI by hand using Swing (its the only way to learn something....(I've certianly nailed Layout Management!!))
    In the stocktickerserver GUI I'm using a JTable to display the details about stocks.
    The user can select a stock and view the details of the stock in another frame. In one panel in the JFrame I've got a JTable listing the history items for the stock (Price, Change, Date).
    Is it possible to color the rows of the JTable according to the value of the change column (or at least the value I insert there)?
    e.g
    if (change > 0){
    Blue;
    else{
    if (change < 0){
    Red;
    else{
    Green;
    I'm completly ignorant on how to achieve this (or even if its possible at all) so all your ideas welcome.
    Any help much appreciated
    Pete
    P.S.
    The Stock History is a class that I store in a [private] Vector in the Stock Class.
    For the selected Stock I loop through this vector getting the items (using various accessor methods)
    I extract the values from the return StockHistory object and build a DefaultTableModel from these
    Then I call JTable.setModel(theModel) to build the table

    implement TableCellRenderer and change foreground of the Renderer in the method getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) . Install this renderer to your table.

  • How to select a specific cell in a JTable?

    Hi there,
    in a JTable, I would like to select a specific cell (to highlight it) from a JButton.
    Here a sample code...
    Who could help me to fill it?
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableSelection{
        public static void main (String args[]) {
          JFrame frame = new MyFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.show();
    class MyFrame extends JFrame{
      public MyFrame(){
        setTitle("TableSelection");
        setSize(WIDTH,HEIGHT);
        DefaultTableModel myModel = new DefaultTableModel(2,2);
        JTable myTable = new JTable(myModel);
        myTable.setCellSelectionEnabled(true);
        JButton button00 = new JButton("select 0,0");
        button00.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (0,0)");
         //--- what code is required to select the cell(0,0)?
        JButton button11 = new JButton("select 1,1");
        button11.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (1,1)");
         //--- what code is required to select the cell(1,1)?
        Box myBox = new Box(BoxLayout.Y_AXIS);
        myBox.add(new JScrollPane(myTable));
        myBox.add(button00);
        myBox.add(button11);
        getContentPane().add(myBox, BorderLayout.CENTER);
      private static final int WIDTH=200;
      private static final int HEIGHT=200;
    }Thanks a lot for your help.
    Denis

    Use the addColumnSelectionInterval(int index1, int index2)method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addColumnSelectionInterval(int,%20int)
    and the addRowSelectionInterval(int index1, int index2) method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addRowSelectionInterval(int,%20int)
    Hope that helped.
    afotoglidis

  • Create a JTable based on an ArrayList containing instances of a class.

    I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.
    The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
         public TableDemo() {
              super(new GridLayout(1, 0));
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Add the scroll pane to this panel.
              add(scrollPane);
         class MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return list.size();
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   MyObject object = list.get(row);
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
          * 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("TableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableDemo newContentPane = new TableDemo();
              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();
    }

  • Error in updating Jtable Database

    package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
    hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
    Error setting value at row 1 column 0 with value soup2
    java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
    at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
    at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
    at desktopapplication1.Datab.setValueAt(Datab.java:104)
    at javax.swing.JTable.setValueAt(JTable.java:2719)
    at javax.swing.JTable.editingStopped(JTable.java:4721)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
    at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
    at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
    at java.awt.Component.processEvent(Component.java:6040)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
    at java.awt.Component.dispatchEventImpl(Component.java:4502)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    my db is like
    RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
    soup 3 2 11 fish
    chocolate 3 2 44 dessert
    Edited by: kainard on Aug 1, 2010 2:31 PM
    Edited by: kainard on Aug 1, 2010 2:37 PM

    Can you explain why you declare
    private Connection conn;
    private Statement st;
    private ResultSet rs;
    private ResultSetMetaData rsmd;
    as private

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    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.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Display data in JTable

    I am trying to display data from database into the JTable swing component. I can see the table and the heading coming from the vector. I cannot see why the data from the databse table is not loaded on to the Jtable. I just get a table with 6 rows blank.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class dataTable extends JApplet
    String dbdriver="jdbc:oracle:thin:@ds1.ctateu.edu:1521:wpac";
    String dbuser="system";
    String dbpass="pass";
    Container c;
    JScrollPane jsp;
    JTable table;
    int v,h;
    Connection connection;
    Statement stmt;
    ResultSet rs;
    String param_start,param_end, param_disp_start, param_disp_end,param_shortdesc, param_longdesc;
    public void init()
    c= getContentPane();
    c.setLayout (new BorderLayout());
    v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    Vector heading = new Vector();
    heading.addElement("Event Start Date");
    heading.addElement("Event End Date");
    heading.addElement("Display Start Date");
    heading.addElement("Display End Date");
    heading.addElement("Short Description");
    heading.addElement("Long Description");
    Vector data = new Vector();
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection=DriverManager.getConnection(dbdriver,dbuser,dbpass);
    stmt=connection.createStatement();
    rs= stmt.executeQuery("select * from univevents");
    while(rs.next())
    param_start = rs.getString("start_date");
    param_end = rs.getString("end_date");
    param_disp_start = rs.getString("display_start");
    param_disp_end =rs.getString("display_end");
    param_shortdesc = rs.getString("short_desc");
    param_longdesc = rs.getString("long_desc");
    catch (Exception e)
    //JOptionPane.showMessageDialogue("Exception: "+e.getMessage());
    data.addElement(param_start);
    data.addElement(param_end);
    data.addElement(param_disp_start);
    data.addElement(param_disp_end);
    data.addElement(param_shortdesc);
    data.addElement(param_longdesc);
    table = new JTable(data, heading);
    jsp = new JScrollPane(table,v,h);
    //Add scrollpane to container
    c.add("Center",jsp);
    }//init
    }//JApplet

    Your data vector should be a Vector of Vectors.
    I think you need to change your loop to look something like this:
    while(rs.next())
        Vector row = new Vector();
        row.addElement( rs.getString("start_date") );
        row.addElement( rs.getString("end_date") );
        row.addElement( rs.getString("display_start") );
        row.addElement( rs.getString("display_end") );
        row.addElement( rs.getString("short_desc") );
        row.addElement( rs.getString("long_desc") );
        data.addElement( row );
    } Then remove your data.addElement() statements found outside the loop.

  • Refresh data in a jtable when data changes

    I have a jtable grdTable and a tableModel mytableModel which extend abstract table model
    I have a jcheckbox in the column 1 which i want to uncheck all
    I am doing the following.The data is changed ,I could see by doing susyem.out.println() but the data in the table does not refreshes.
    public void showTablechanges()
    TableModel tm = grdTable.getModel;
    for(int i=0 ;i<grdTable.getRowCount();i++)
    grdTable.setValueAt(Boolean.FALSE, i, 1);
    ( (MyTableModel)tm).fireTableDataChanged();
    grdTable.repaint();
    What am i missing or what wrong I am doing.How can i make the data refresh.
    I tried do a sys out after seting the value and it is showing as false but the checkbox is still checked.I have tried a lot of things but I am not able to refresh the jtable.
    Please please help.
    Thanks

    Thanks so much for the reply I read the links.I modified my code as
    public void showTablechanges() {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    TableModel tm = grdTable.getModel;
    for (int i = 0; i < grdTable.getRowCount(); i++) {
    grdTable.setValueAt(Boolean.FALSE, i, 1);
    ((MyTableModel) tm).fireTableDataChanged();
    grdTable.repaint();
    This makes no difference.What strange thing is happening out of 12 checkboxes ,11 are unchecked but the first one always remains checked.EVen without the
    invoke later 11 are unchecked and 1 remains checked
    This method is in a panel and this panel is invoked from another MAin panel which has a changelistener for this panel.
    i.e if the method above is in myPanel.java then in my main panel,I have
    myPanel.addChangeListener(this)
    Also if i remove the line
    ((MyTableModel) tm).fireTableDataChanged();
    All checkboxes remains checked.
    I am really confused and this looks very tough to me ,Can you find out what is wrong
    Thanks,

  • Refresh jTable after inserting new data into the Database

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

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

  • To refresh the contents in JTextArea on selection of a row in JTable.

    This is the block of code that i have tried :
    import java.awt.GridBagConstraints;
    import java.awt.SystemColor;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.DefaultTableModel;
    import ui.layouts.ComponentsBox;
    import ui.layouts.GridPanel;
    import ui.layouts.LayoutConstants;
    import util.ui.UIUtil;
    public class ElectronicJournal extends GridPanel {
         private boolean DEBUG = false;
         private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
         private GridPanel jGPanel = new GridPanel();
         private GridPanel jGPanel1 = new GridPanel();
         private GridPanel jGPanel2 = new GridPanel();
         DefaultTableModel model;
         private JLabel jLblTillNo = UIUtil.getHeaderLabel("TillNo :");
         private JLabel jLblTillNoData = UIUtil.getBodyLabel("TILL123");
         private JLabel jLblData = UIUtil.getBodyLabel("Detailed View");
         private JTextArea textArea = new JTextArea();
         private JScrollPane spTimeEntryView = new JScrollPane();
         private JScrollPane pan = new JScrollPane();
         String html= " Item Description: Price Change \n Old Price: 40.00 \n New Price: 50.00 \n Authorized By:USER1123 \n";
         private JButton jBtnExporttoExcel = UIUtil.getButton(85,
                   "Export to Excel - F2", "");
         final String[] colHeads = { "Task No", "Data", "User ID", "Date Time",
                   "Description" };
         final Object[][] data = {
                   { "1", "50.00", "USER123", "12/10/2006 05:30", "Price Change" },
                   { "2", "100.00", "USER234", "15/10/2006 03:30", "Price Change12345"},
         final String[] colHeads1 = {"Detailed View" };
         final Object[][] data1 = {
                   { "Task:Price Change", "\n"," Old Price:50.00"," \n ","New Price:100.00"," \n" }
         JTable jtblTimeEntry = new JTable(data, colHeads);
         JTable jTbl1 = new JTable(data1,colHeads1);
         ComponentsBox jpBoxButton = new ComponentsBox(LayoutConstants.X_AXIS);
         public ElectronicJournal() {
              super();
              jtblTimeEntry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = jtblTimeEntry.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    System.out.println("Row " + selectedRow
    + " is now selected.");
    textArea.append("asd \n 123 \n");
    } else {
         jtblTimeEntry.setRowSelectionAllowed(false);
              if (DEBUG) {
                   jtblTimeEntry.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
         printDebugData(jtblTimeEntry);
              initialize();
         private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
         private void initialize() {
              this.setSize(680, 200);
              this.setBackground(java.awt.SystemColor.control);
              jBtnExporttoExcel.setBackground(SystemColor.control);
              ComponentsBox cmpRibbonHORZ = new ComponentsBox(LayoutConstants.X_AXIS);
              cmpRibbonHORZ.addComponent(jBtnExporttoExcel, false);
              jpBoxButton.add(cmpRibbonHORZ);
              this.addFilledComponent(jGPanel, 1, 1, 1, 1, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel1, 2, 1, 11, 5, GridBagConstraints.BOTH);
              this.addFilledComponent(jGPanel2, 2, 13, 17, 5, GridBagConstraints.BOTH);
              jGPanel.setSize(650, 91);
              jGPanel.setBackground(SystemColor.control);
              jGPanel.addFilledComponent(jLblTillNo,1,1,GridBagConstraints.WEST);
              jGPanel.addFilledComponent(jLblTillNoData,1,10,GridBagConstraints.BOTH);
              jGPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0));
              jGPanel1.setBackground(SystemColor.control);
              jGPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              spTimeEntryView.setViewportView(jtblTimeEntry);
              jGPanel1.addFilledComponent(spTimeEntryView, 1, 1, 11, 4,
                        GridBagConstraints.BOTH);
              jGPanel2.addFilledComponent(jLblData,1,1,GridBagConstraints.WEST);
              jGPanel2.setBackground(SystemColor.control);
              jGPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0,
                        0));
              //textArea.setText(html);
              pan.setViewportView(textArea);
         int selectedRow = jTbl1.getSelectedRow();
              System.out.println("selectedRow ::" +selectedRow);
              int colCount = jTbl1.getColumnCount();
              System.out.println("colCount ::" +colCount);
              StringBuffer buf = new StringBuffer();
              System.out.println("Out Of For");
              /*for(int count =0;count<colCount;count++)
              {System.out.println("Inside For");
              buf.append(jTbl1.getValueAt(selectedRow,count));
              // method 1 : Constructs a new text area with the specified text. 
              textArea  =new JTextArea(buf.toString());
              //method 2 :To Append the given string to the text area's current text.   
             textArea.append(buf.toString());
              jGPanel2.addFilledComponent(pan,2,1,5,5,GridBagConstraints.BOTH);
              this.addAnchoredComponent(jpBoxButton, 7, 5, 11, 5,
                        GridBagConstraints.CENTER);
    This code displays the same data on the JTextArea everytime i select each row,but my requirement is ,it has to refresh and display different datas in the JTextArea accordingly,as i select each row.Please help.Its urgent.
    Message was edited by: Samyuktha
    Samyuktha

    Please help.Its urgentThen why didn't you use the formatting tags to make it easier for use to read the code?
    Because of the above I didn't take a close look at your code, but i would suggest you should be using a ListSelectionListener to be notified when a row is selected, then you just populate the text area.

Maybe you are looking for