JTable  - ComboBox problem

From using a tutorial from a website.. it places a JComboBox in first column the ComboBox elements are: "item1", "item2", "item3", all rows are given these values.
How can I do it such that JComboBox have different values for each row?
JTable table = new JTable();
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    // Add some columns
    model.addColumn("A", new Object[]{"item1"});
    model.addColumn("B", new Object[]{"item2"});
    // These are the combobox values
    String[] values = new String[]{"item1", "item2", "item3"};
    // Set the combobox editor on the 1st visible column
    int vColIndex = 0;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    col.setCellEditor(new MyComboBoxEditor(values));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    col.setCellRenderer(new MyComboBoxRenderer(values));
    public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
        public MyComboBoxRenderer(String[] items) {
            super(items);
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                super.setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            // Select the current value
            setSelectedItem(value);
            return this;
    public class MyComboBoxEditor extends DefaultCellEditor {
        public MyComboBoxEditor(String[] items) {
            super(new JComboBox(items));
    }

thank you for informing me, i will be posting question on that, the solution is helpful...but not sufficient..
For ref. the topic is:
http://forum.java.sun.com/thread.jspa?threadID=606573

Similar Messages

  • JTable Combobox dependencies

    i have a jtable with 2 column
    each column has JComboBox for CellRenderer
    the second column is depends on the first one
    means
    if in row 1 , first combo select value 1 , i should have in second combobox thous values 11,12,13,14
    if in row 2 , first combo select value 2 , i should have in second combobox thous values 21,22,23,24
    i wanted to listen to ActionEvent ,ItemEvent ,PopupMenuEvent on the combobox on the Second Combobox
    and before the second combobox is showing replace all available values in the second combobox
    but no matter what property i ask for i cant tell if the combobox is in open or is not
    cause each time i get 2 events
    one for opening second combobox other for selecting value in it
    please help me

    I have no idea how a HierarchyListener would be used to solve this problem.
    FYI, the [Combo Box Table Editor|http://www.camick.com/java/blog.html?name=combo-box-table-editor] was created for this situation.

  • JTable: renderer problem-urgent

    Thanx "pasteven". That url is too good.
    I wrote my own renderer for each cell in JTable that uses JCombobox for rendering purpose. But when i select an item in that combo box, some times renderer is not setting the selected item in that combobox. Sometimes when i change the selection of item in the previous cell,it is getting reflected in all other cells of that particular column.
    Here is my code. Please help me.
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.TableCellEditor.*;
    import javax.swing.table.*;
    import javax.swing.DefaultCellEditor;
    public class Render extends javax.swing.JFrame {
    JTextField textField0=new JTextField();
    JComboBox cmb_Editor1=new JComboBox();
    JComboBox cmb_Editor2=new JComboBox();
    JComboBox cmb_Editor3=new JComboBox();
    EachRowRenderer rend;
    EachRowEditor eee;
    /** Creates new form Render */
    public Render() {
    initComponents ();
    rend=new EachRowRenderer();
    eee=new EachRowEditor(table);
    table.setDefaultRenderer(java.lang.Object.class,rend);
    table.setDefaultEditor(java.lang.Object.class,eee);
    cmb_Editor3.addItem("Y");
    cmb_Editor3.addItem("N");
    eee.setEditorAt(0,1,new DefaultCellEditor(cmb_Editor3));
    eee.setEditorAt(1,1,new DefaultCellEditor(cmb_Editor3));
    eee.setEditorAt(2,1,new DefaultCellEditor(cmb_Editor3));
    eee.setEditorAt(0,2,new DefaultCellEditor(new JCheckBox()));
    rend.add(0,2,new CheckBoxCellRenderer());
    rend.add(0,1,new ComboBoxCellRenderer(cmb_Editor3));
    rend.add(1,1,new ComboBoxCellRenderer(cmb_Editor3));
    rend.add(2,1,new ComboBoxCellRenderer(cmb_Editor3));
    JCheckBox chk=new JCheckBox();
    pack ();
    public class EachRowEditor implements TableCellEditor {
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    JTable table;
    public EachRowEditor(JTable table) {
    this.table = table;
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void setEditorAt(int row,int column, TableCellEditor editor) {
    editors.put(""+row+column,editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    return editor.getTableCellEditorComponent(table,
    value, isSelected, row, column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    selectEditor((MouseEvent)anEvent);
    // editor.isCellEditable(anEvent);
         return true;
    public void addSeperateCellEditorListener(int row,int column,CellEditorListener l) {
    editor=(TableCellEditor)editors.get(""+row+column);
    editor.addCellEditorListener(l);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    selectEditor((MouseEvent)anEvent);
    return editor.shouldSelectCell(anEvent);
    protected void selectEditor(MouseEvent e) {
    int row;
    int column;
    if (e == null) {
    row = table.getSelectionModel().getAnchorSelectionIndex();
    column=table.getSelectionModel().getLeadSelectionIndex();
    } else {
    row = table.rowAtPoint(e.getPoint());
    column=table.columnAtPoint(e.getPoint());
    editor = (TableCellEditor)editors.get(""+row+column);
    if (editor == null) {
    editor = defaultEditor;
    public class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer
    CheckBoxCellRenderer() {
    setHorizontalAlignment(JLabel.CENTER);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setSelected((value != null && ((Boolean)value).booleanValue()));
    setToolTipText("checkbox");
    return this;
    public class TextFieldCellRenderer extends JTextField implements TableCellRenderer
    JTextField textField;
    TextFieldCellRenderer(JTextField textField) {
    this.textField=textField;
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setText((textField.getText() != null) ? textField.getText() : "");
    return textField;
    public class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer
    JComboBox comboBox=null;
    ComboBoxCellRenderer(JComboBox comboBox) {
    this.comboBox=comboBox;
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setSelectedItem(comboBox.getSelectedItem());
    return this;
    public class EachRowRenderer implements TableCellRenderer {
    protected Hashtable renderers;
    protected TableCellRenderer renderer, defaultRenderer;
    public EachRowRenderer() {
    renderers = new Hashtable();
    defaultRenderer = new DefaultTableCellRenderer();
    public void add(int row,int column ,TableCellRenderer renderer) {
    renderers.put(""+row+column,renderer);
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    renderer = (TableCellRenderer)renderers.get(""+row+column);
    if (renderer == null) {
    renderer = defaultRenderer;
    return renderer.getTableCellRendererComponent(table,
    value, isSelected, hasFocus, row, column);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the FormEditor.
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    table.setModel(new javax.swing.table.DefaultTableModel (
    new Object [][] {
    {null, null, null, null},
    {null, null, null, null},
    {null, null, null, null},
    {null, null, null, null}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4"
    Class[] types = new Class [] {
    java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
    public Class getColumnClass (int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(table);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit (0);
    * @param args the command line arguments
    public static void main (String args[]) {
    new Render ().show ();
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help me.

    I ran into the same problem in Java 1.4. The problem is that the JTable is not feeding the initial value to the cell editor. I found the following workaround. You have to override the JTable method prepareEditor() like this:
    <CODE>
    public Component prepareEditor(TableCellEditor editor, int row, int column) {
    Component ret = super.prepareEditor(editor, row, column);
    // Translate column to the data model coordinates by using the
    // identifier. We'll check only for the JComboBox columns (in
    // this example columns 8 and 9).
    int col = 0;
    String id = (String)getColumnModel().getColumn(column).getIdentifier();
    if ( id.equals( tableModel.getColumnName(8) ) )
    col = 8;
    else if ( id.equals( tableModel.getColumnName(9) ) )
    col = 9;
    if (col == 8 || col == 9) {
    String item = (String)tableModel.getValueAt(row, col);
    ((JComboBox)((DefaultCellEditor)editor).getComponent()).setSelectedItem( item );
    return ret;
    </CODE>
    You have to translate from table coordinates to table model coordinates in case the user reorders column - if you don't allow this for your table then you won't have to do this.

  • JTable setViewportView problems

    Hey there.
    Just a small question. I've made an application. A part of it is a JScrollPanel with a JTable. I update the JTable with the method setViewportView everytime i need to.
    The problem is that i have a combobox in one of my coloumns. On my combo i have a popupmenulistener. In the method popupmenuwillbecomeinvisible i have implemented some code and also a call to the method setViewportView. Everytime i use this combo i get an exception. nullpointer exception in JComponent. It's only when i use the combo because i call the method setViewportView ellswhere....so any idea what could be my problem??
    Thanks!!
    :o) Ellyton

    hmmm, sometimes doing a redesign is painfull in the short term but invaluable in the mid/long term. it might allow you to change/extend your code (aside from debugging is much easier).
    in general when using Swing you should make a clear distinction between your data model (table model, tree model, list model etc) and your control (JTable, JTree, Jlist, etc). that way, changing your data, like in your case, becomes very easy, as well as accessing it in different ways.
    you say, you have to "update the entire table everytime...", what do you mean by this? the table data? if so, simply change the content of your array/vector in the table model and fire a tableDataChanged event. the JTable will redraw itself with the new/changed data.
    thomas

  • JTable size problems due to layout/grid...how can I fix?

    This is my code. When the button "Modify Entries" is pressed, it shows a JTable that imports a file called, "entries.data". The items in this file can be read and saved using this program. The problem is that the table is so small when it first opens. How can I set all my buttons to the very bottom of the form and make the table take up more space at the top? It looks to me as if this layout is treating it with the same dimensions as the buttons'.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.util.*;
    import java.io.*;
    public class CPT extends JPanel implements ActionListener
        protected JButton ModifyEntriesButton, ViewEntriesButton, SearchEntriesButton, SaveButton, BackButton;
        private final static String newline = "\n";
        private DefaultTableModel model;
        public CPT ()
            super (new GridLayout (10, 0));
            model = new PropertiesModel ("entries.data");
            ModifyEntriesButton = new JButton ("Modify Entries");
            ModifyEntriesButton.setVerticalTextPosition (AbstractButton.TOP);
            ModifyEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ModifyEntriesButton.setToolTipText ("Click this button to modify database entries.");
            ModifyEntriesButton.setMnemonic (KeyEvent.VK_M);
            ModifyEntriesButton.setActionCommand ("ModifyEntries");
            ModifyEntriesButton.addActionListener (this);
            ViewEntriesButton = new JButton ("View Entries");
            ViewEntriesButton.setVerticalTextPosition (AbstractButton.CENTER);
            ViewEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ViewEntriesButton.setToolTipText ("Click this button to add view all database entries.");
            ViewEntriesButton.setMnemonic (KeyEvent.VK_V);
            ViewEntriesButton.setActionCommand ("ViewEntries");
            ViewEntriesButton.addActionListener (this);
            SearchEntriesButton = new JButton ("Search Entries");
            SearchEntriesButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            SearchEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            SearchEntriesButton.setToolTipText ("Click this button to search through all database entries.");
            SearchEntriesButton.setMnemonic (KeyEvent.VK_S);
            SearchEntriesButton.setActionCommand ("SearchEntries");
            SearchEntriesButton.addActionListener (this);
            SaveButton = new JButton ("Save");
            SaveButton.setVerticalTextPosition (AbstractButton.TOP);
            SaveButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            SaveButton.setToolTipText ("Click this button to save database entries.");
            SaveButton.setMnemonic (KeyEvent.VK_S);
            SaveButton.setActionCommand ("Save");
            SaveButton.addActionListener (this);
            BackButton = new JButton ("Back");
            BackButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            BackButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            BackButton.setToolTipText ("Click this button to return to the main menu.");
            BackButton.setMnemonic (KeyEvent.VK_B);
            BackButton.setActionCommand ("Back");
            BackButton.addActionListener (this);
            add (ModifyEntriesButton);
            add (ViewEntriesButton);
            add (SearchEntriesButton);
        class PropertiesModel extends DefaultTableModel
            public PropertiesModel (String filename)
                addColumn ("Item Number");
                addColumn ("Description");
                addColumn ("Price");
                //Fill model with data from property file
                Properties props = readFile (filename);
                if (props != null)
                    Enumeration coll = props.keys ();
                    while (coll.hasMoreElements ())
                        String property = (String) coll.nextElement ();
                        String value = props.getProperty (property, "");
                        addRow (new Object[]
                            property, value
        private Properties readFile (String filename)
            try
                Properties props = new Properties ();
                props.load (new FileInputStream (filename));
                return props;
            catch (IOException ioe)
                return null;
        private boolean saveFile (String filename)
            try
                Properties props = new Properties ();
                for (int i = 0 ; i < model.getRowCount () ; i++)
                    props.put (model.getValueAt (i, 0), model.getValueAt (i, 1));
                props.store (new FileOutputStream (filename), null);
                return true;
            catch (IOException ioe)
                return false;
        public void actionPerformed (ActionEvent e)
            if ("ModifyEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (new JScrollPane (new JTable (model)), BorderLayout.CENTER);
                add (SaveButton);
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("ViewEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("SearchEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("Back".equals (e.getActionCommand ()))
                removeAll ();
                add (ModifyEntriesButton);
                add (ViewEntriesButton);
                add (SearchEntriesButton);
                invalidate ();
                updateUI ();
            if ("Save".equals (e.getActionCommand ()))
                if (saveFile ("entries.data"))
                    JOptionPane.showMessageDialog (null, "File saved successfully.");
                else
                    JOptionPane.showMessageDialog (null, "File could not be saved!");
        // Create the GUI and show it. For thread safety,
        // this method should be invoked from the
        // event-dispatching thread.
        private static void createAndShowGUI ()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated (true);
            //Create and set up the window.
            JFrame frame = new JFrame ("Swisha Computer House");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new CPT ();
            newContentPane.setOpaque (true); //content panes must be opaque
            frame.setContentPane (newContentPane);
            //Display the window.
            frame.pack ();
            frame.setSize (300, 300);
            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 ();
    }Hey, and if anyone knows how to get the first column's numbers from the file to show up in descending order (1 through to, say, 500), please let me know.
    Thank you for any help.

    It looks to me as if this layout is treating it with the same dimensions as the buttons'.Thats the way a GridLayout works.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers. You can mix an match individual Layout Managers to get the effect desired.
    I would suggest you need to change your design. Your code for continually removing and adding components is not the best design. You should probably have a panel with all your buttons. Then you would have different panels for each of your sub functions. The display of these panels would be controlled by a Card Layout. The tutorial has working examples of this.
    You can't use a Properties file to save data from the table (at least not the way you are attempting to use it). I gave you a solution in your last posting.

  • 1.2 / 1.3 JTable getHeaderRenderer() problem

    Hi,
    I've got a Swing Applet which is currently running on 1.2 which I'd now like to upgrade to 1.3 in order to take advantage of the new functionality.
    I've done some preliminary testing, and am encountering problems with the upgrades made to the JTable (see http://java.sun.com/j2se/1.3/docs/guide/swing/JTableChanges.html) in 1.3
    My code uses column.getHeaderRenderer().getTableCellRendererComponent() to get the Header renderer. Unfortunately, the 1.3 implementation has changed so that this now returns null. 1.3 uses table.getTableHeader().getDefaultRenderer() instead.... but this bit of the API doesn't exist in 1.2
    So, please can someone suggest how I might get the code to work for both 1.2 & 1.3 simultaneously?
    Cheers
    RT

    One of the quickest ways around would be to set the header renderer for each column:
    TableCellRenderer headerRenderer = new DefaultTableCellRenderer();
    for(...)
      column.setHeaderRenderer(headerRenderer);
    }That way the column's own renderer would always be used in preference to the default one for a JTableHeader. You might need to play around with the look of it, though.
    The more complete solution would be to use reflection to determine whether the "1.3" method exists and call it if is does. It would be a nasty way to do things, though, and be a maintenance issue in the future.
    try
      Class headerClass = tableHeader.getClass();
      Method method = headerClass.getDeclaredMethod("getDefaultRenderer", new Class[] {});
      headerRenderer = method.invoke(tableHeader, new Object[] {});
    catch(NoSuchMethodException e)
      headerRenderer = column.getHeaderRenderer();
    }Hope this helps.

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

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

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

  • Jtable Update problem .. Please help !!!!!!!!

    Hi ,
    I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
    But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
    Here is the code .... Please see it and tell me if it is possible :
    package newpackage;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Dimension;
    import java.text.*;
    import newpackage.ExcelExporter;
    import java.awt.Dimension;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Random.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    public class tab7le extends javax.swing.JFrame {
        Vector columnNames = new Vector();
        Vector data = new Vector();
        Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        /** Creates new form tab7le */
        public tab7le() {
            populate();
            initComponents();
           public void updateDB(){
                     try{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch (ClassNotFoundException e){
                System.out.println("Cannot Load Driver!");
          try{
             String url = "jdbc:odbc:FAMS";
             con = DriverManager.getConnection(url);
             stat = con.createStatement();
             rs = stat.executeQuery("Select * from SubAllot");
             deletedKeys = new Vector();
             newRows = new Vector();
             myM = rs.getMetaData();
             tableName = myM.getTableName(1);
             li_cols = myM.getColumnCount();
             dbColNames = new String[li_cols];
             for(int col = 0; col < li_cols; col ++){
                dbColNames[col] = myM.getColumnName(col + 1);
             allRows = new Vector();
             while(rs.next()){
                newRow = new Vector();
                for(int i = 1; i <= li_cols; i++){
                   newRow.addElement(rs.getObject(i));
                } // for
                allRows.addElement(newRow);
             } // while
          catch(SQLException e){
             System.out.println(e.getMessage());
    String updateLine[] = new String[dbColNames.length];
          try{
             DatabaseMetaData dbData = con.getMetaData();
             String catalog;
             // Get the name of all of the columns for this table
             String curCol;
             colNames = new Vector();
             ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
             while (rset1.next()) {
                curCol = rset1.getString(4);
                colNames.addElement(curCol);
             rset1.close();
             pKeyCol = colNames.firstElement().toString();
             // Go through the rows and perform INSERTS/UPDATES/DELETES
             int totalrows;
             totalrows = allRows.size();
             String dbValues[];
             Vector currentRow = new Vector();
             pkValues = new String[allRows.size()];
             // Get column names and values
             for(int i=0;i < totalrows;i++){
                currentRow = (Vector) allRows.elementAt(i);
                int numElements = currentRow.size();
                dbValues = new String[numElements];
                for(int x = 0; x < numElements; x++){
                   String classType = currentRow.elementAt(x).getClass().toString();
                   int pos = classType.indexOf("String");
                   if(pos > 0){ // we have a String
                      dbValues[x] = "'" + currentRow.elementAt(x) + "'";
                      updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                        pkValues[i] = currentRow.elementAt(x).toString() ;
                   pos = classType.indexOf("Integer");
                   if(pos > 0){ // we have an Integer
                      dbValues[x] = currentRow.elementAt(x).toString();
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString();
                      else{
                         updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                   pos = classType.indexOf("Boolean");
                   if(pos > 0){ // we have a Boolean
                      dbValues[x] = currentRow.elementAt(x).toString();
                      updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString() ;
                } // For Loop
                // If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
                int numNewRows = newRows.size();
                int insertRow = 0;
                boolean newRowFound;
                for (int z = 0;z < numNewRows;z++){
                   insertRow = ((Integer) newRows.get(z)).intValue();
                   if(insertRow == i+1){
                      StringBuffer InsertSQL = new StringBuffer();
                      InsertSQL.append("INSERT INTO " + tableName + " (");
                      for(int zz=0;zz<=dbColNames.length-1;zz++){
                         if (dbColNames[zz] != null){
                            InsertSQL.append(dbColNames[zz] + ",");
                      // Strip out last comma
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      InsertSQL.append(" VALUES(" + pkValues[i] + ",");
                      for(int c=1;c < dbValues.length;c++){
                         InsertSQL.append(dbValues[c] + ",");
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      System.out.println(InsertSQL.toString());
                      stat.executeUpdate(InsertSQL.toString());
                      ibRowInserted=true;
                } // End of INSERT Logic
                // If row has not been INSERTED perform an UPDATE
                if(ibRowInserted == false){
                   StringBuffer updateSQL = new StringBuffer();
                   updateSQL.append("UPDATE " + tableName + " SET ");
                   for(int z=0;z<=updateLine.length-1;z++){
                      if (updateLine[z] != null){
                         updateSQL.append(updateLine[z]);
                   // Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
                   updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
                   updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
                   System.out.println(updateSQL.toString());
                   stat.executeUpdate(updateSQL.toString());
                   } //for
             catch(Exception ex){
                System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
             // Delete records from the DB
             try{
                int numDeletes = deletedKeys.size();
                String deleteSQL;
                for(int i = 0; i < numDeletes;i++){
                   deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
                                                ((Integer) deletedKeys.get(i)).toString();
                System.out.println(deleteSQL);
                   stat.executeUpdate(deleteSQL);
                // Assume deletes where successful. Recreate Vector holding PK Keys
                deletedKeys = new Vector();
             catch(Exception ex){
                System.out.println(ex.getMessage());
        public void populate()
            try
                //  Connect to the Database
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
                System.out.println("ok1");
                //  Read data from a table
                String sql;
                 sql = "Select * from SubAllot";
                 System.out.println("ok1");
                Statement stmt = con.createStatement();
                System.out.println("ok1");
                ResultSet rs = stmt.executeQuery( sql );
                System.out.println("ok1");
                ResultSetMetaData md = rs.getMetaData();
                System.out.println("ok1");
                int columns = md.getColumnCount();
                for(int i = 0;i<columns;i++){
                    columnNames.addElement(md.getColumnName(i+1));
                    System.out.println("ok2");
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <columns+1; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
            catch(Exception e){
                e.printStackTrace();
                 public void dropmenu(JTable table,TableColumn subpref1) {
            //Set up the editor for the sport cells.
            JComboBox comboBox = new JComboBox();
          for (int i = 0;i<=20;i++)
           comboBox.addItem(i);
            subpref1.setCellEditor(new DefaultCellEditor(comboBox));
            //Set up tool tips for the sport cells.
            DefaultTableCellRenderer renderer =
                    new DefaultTableCellRenderer();
            renderer.setToolTipText("Click for combo box");
            subpref1.setCellRenderer(renderer);
                       abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    Object val = model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    data, columnNames
    jScrollPane1.setViewportView(table);
    //populate();
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    dropmenu(table, table.getColumnModel().getColumn(11));
    jButton1.setText("Update");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Ex");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(92, 92, 92)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(347, 347, 347)
    .addComponent(jButton1)
    .addGap(115, 115, 115)
    .addComponent(jButton2)))
    .addContainerGap(73, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(47, 47, 47)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(58, 58, 58)
    .addComponent(jButton1)
    .addContainerGap(83, Short.MAX_VALUE))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addGap(65, 65, 65))))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    updateDB(); // TODO add your handling code here:
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
    pathToDesktop = pathToDesktop + "//Final Allotment.xls";
    ExcelExporter exp = new ExcelExporter();
    exp.exportTable(table, new File(pathToDesktop));
    JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
    catch (IOException ex) {
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    } // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new tab7le().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help !!!!!!!!
    Thanks in advance.....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
    Why post code with access to a database? We can't access the database.
    Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
    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.

  • JTable Combobox editor with PrppertychangeListener

    Hello,
    I need a help from experts.
    I have a JTable. In the java table i need to have a ComboBox editor for example on the second column. And when i am changing value in the combobox i need to to do some calculations in JTable object.
    To setup a PropertyChangeListener on combo object is not what i want, because i can not make calcultions inside JTable.
    I need ComboBox based editor for JTable with property change listener.
    Can anybody point me to some example o sugest something?
    Thanks a lot

    Sollution
    package kelias.table.editor;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JTable;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.Component;
    import kelias.ComboBox.MyDBComboBox;
    Implements a cell editor that uses a formatted text field
    to edit Integer values.
    public class CarJobEditor extends DefaultCellEditor implements ItemListener
    MyDBComboBox comboJobs;
    //Darbo kiekis
    String jobQuantity=new String();
    //Lentel�
    JTable tableTmp;
    //Einamoji eilut�
    int rowTmp;
    int jobQColNumber;
    int resultColIndex;
    public CarJobEditor(int jobQColNumber,int resultColIndex)
    super(new MyDBComboBox());
    this.jobQColNumber=jobQColNumber;
    this.resultColIndex=resultColIndex;
    comboJobs = (MyDBComboBox) getComponent();
    comboJobs.loadData(kelias.db.DBStrings.selectJobsForCombo());
    comboJobs.addItemListener(this);
    //Override to invoke setValue on the formatted text field.
    public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected,int row, int column)
         jobQuantity=(String)table.getValueAt(row,jobQColNumber);
         this.tableTmp=table;
         this.rowTmp=row;
    MyDBComboBox tmp = (MyDBComboBox)super.getTableCellEditorComponent(table, value, isSelected, row, column);
    tmp.setSelectedItem(value);
    return tmp;
    public void itemStateChanged(ItemEvent event)
         if(event.getStateChange() == ItemEvent.SELECTED)
              if (!this.jobQuantity.equals(""))
                   float price=kelias.db.DBGetData.selectJobPricePM(comboJobs.getSelectedItem());
                   float quantity=Float.parseFloat((String)jobQuantity);
                   float f = (float) (Math.round(price*quantity*100.0f)/100.0f);
                   tableTmp.setValueAt(f,rowTmp,resultColIndex);
    }

  • JTable printing problem

    Hi , I have a problem add printing routine for printing to this code.
    Sombody help me.
    I no post all code but my prube no functioned.
    thanks you
    code :
    package com.froses.tablemodels;
    * SimpleDBTable.java
    * A demonstration of using ODBC to read data from an Access database
    * and display the values in a JTable.
    * This file requires that the new.mdb file exists and has been mapped
    * using ODBC to a datastore named 'newdb' with blank username and password.
    * Gordon Branson January 2004
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class SimpleDBTable extends JPanel {
    private boolean DEBUG = true;
    private int rows = 10, cols = 5;
    private String url = "jdbc:odbc:Sego";
    private Connection con;
    private Statement stmt;
    private JButton btnRead, btnDelete, btnWrite, btnClose;
              /* Setup the table column names */
    private String[] columnNames = {"Medico",
    "Descripci�n",
    "Obra social",
    "Items",
    "Codigo"};
              /* declare an Object array large enough to hold the database table */
    private Object[][] data = new Object[rows][cols];
    private JTable table;
    public SimpleDBTable() {
    super(new BorderLayout());
    /* Load ODBC diver */
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
              /* create the JTable */
    table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 300));
    /* Now read from the database */
    populateTable();
    if (DEBUG) {
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    printDebugData();
    //Create the Title Label.
    JLabel title = new JLabel("Database Access in Java");
    title.setFont(new java.awt.Font("Arial", 1, 24));
    title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    //Add the label to this panel.
    add("North",title);
    //Create the scroll pane and add the JTable to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this panel.
    add("Center",scrollPane);
    // Create a button panel with a default layout
    JPanel buttons = new JPanel();
    // Create the buttons
    btnRead = new JButton("Read");
    btnClose = new JButton("Close");
    btnWrite = new JButton("Write");
    btnDelete = new JButton("Delete");
    // Add action listeners
    btnRead.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    populateTable();
    btnDelete.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    deleteTable();
    btnWrite.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    writeTable();
    btnClose.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    System.exit(0);
    // Add the buttons to the button panel
    buttons.add(btnRead);
    buttons.add(btnWrite);
    buttons.add(btnDelete);
    buttons.add(btnClose);
    // Add the buttons panel to main panel
    add("South",buttons);
    private void populateTable(){
         /* Define the SQL Query to get all data from the database table */
    String query = "SELECT * FROM Datos";
    /* First clear the JTable */
    clearTable();
    /* get a handle for the JTable */
    javax.swing.table.TableModel model = table.getModel();
    int r = 0;
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
    stmt = con.createStatement();
    /* run the Query getting the results into rs */
                   ResultSet rs = stmt.executeQuery(query);
                   while ((rs.next()) && (r<rows)) {
                        /* for each row get the fields
                        note the use of Object - necessary
                        to put the values into the JTable */
                   Object nm = rs.getObject("Medico_solic");
                   Object sup = rs.getObject("Descip_Item");
                   Object pri = rs.getObject("Obra_Social");
                   Object sal = rs.getObject("M�dico_opera");
                   Object tot = rs.getObject("Codigo_estudio");
                   model.setValueAt(nm, r, 0);
                   model.setValueAt(sup, r, 1);
                   model.setValueAt(pri, r, 2);
                   model.setValueAt(sal, r, 3);
                   model.setValueAt(tot, r, 4);
                   r++;
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    private void deleteTable(){
         emptyTable();
         clearTable();
    private void emptyTable(){
         /* Define the SQL Query to get all data from the database table */
    String query = "DELETE * FROM COFFEES";
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
    stmt = con.createStatement();
    /* run the Query */
                   stmt.executeUpdate(query);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    /* private void writeTable(){
         /* First clear the table */
    /*      emptyTable();
         PreparedStatement insertRow;// = con.prepareStatement(
         String insertString = "INSERT INTO COFFEES " +
                                  "VALUES (?, ?, ?, ?, ?)";
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();
    Integer sup, sal, tot;
    Double pri;
    Object o;
    if(DEBUG) System.out.println("\nDoing Write...");
    try {
    /* connect to the database */
    /* con = DriverManager.getConnection(url, "", "");
    insertRow = con.prepareStatement(insertString);
         for (int r=0; r < numRows; r++) {
              if (model.getValueAt(r, 0) != null){
                   insertRow.setString(1, (String) model.getValueAt(r, 0));
                   //o = model.getValueAt(r, 1);
                   if(DEBUG) System.out.println(model.getValueAt(r, 1).toString());
                   sup = new Integer((String) model.getValueAt(r, 1));
                   insertRow.setInt(2, sup.intValue());
                   pri = new Double((String) model.getValueAt(r, 2));
                   insertRow.setDouble(3, pri.doubleValue());
                   sal = new Integer((String) model.getValueAt(r, 3));
                   insertRow.setInt(4, sal.intValue());
                   tot = new Integer((String) model.getValueAt(r, 4));
                   insertRow.setInt(5, tot.intValue());
                   insertRow.executeUpdate();
                   System.out.println("Writing Row " + r);
    insertRow.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    clearTable();
    private void writeTable(){
         /* First clear the table */
         emptyTable();
         Statement insertRow;// = con.prepareStatement(
         String baseString = "INSERT INTO Datos " +
                                  "VALUES ('";
         String insertString;
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();
    Integer sup, sal, tot;
    Double pri;
    Object o;
    if(DEBUG) System.out.println("\nDoing Write...");
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
         for (int r=0; r < numRows; r++) {
              if (model.getValueAt(r, 0) != null){
                   insertString = baseString + model.getValueAt(r, 0)+"',";
                   insertString = insertString + model.getValueAt(r, 1)+",";
                   insertString = insertString + model.getValueAt(r, 2)+",";
                   insertString = insertString + model.getValueAt(r, 3)+",";
                   insertString = insertString + model.getValueAt(r, 4)+");";
                   if(DEBUG) System.out.println(insertString);
              insertRow = con.createStatement();
                   insertRow.executeUpdate(insertString);
                   System.out.println("Writing Row " + r);
    insertRow.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    clearTable();
    private void clearTable(){
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    for (int i=0; i < numRows; i++) {
    for (int j=0; j < numCols; j++) {
    model.setValueAt(null, i, j);
    private void printDebugData() {
    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("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("SimpleDBTable");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    SimpleDBTable newContentPane = new SimpleDBTable();
    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();
    }

    http://forum.java.sun.com/thread.jspa?threadID=626207

  • Intermittent JTable Selection Problem

    Hi,
    Everyone once in a while, under NT with 1.4.x, I have problems selecting and highlighting row under JTable. It happens a good bit, but this does not happen all the time. When the table is buggy, it does not keep the row selected nor does it highlight the row. You may have the row selected on a mousedown, but once you release the mouse it's done.
    Since this is happening for a variety of JTable's I didn't bother to send Java code. Has anyone else encountered this sort of thing? Or does anyone know what I should be looking at?
    The intermittent part is what's killing me. It makes it hard to track down with any high degreee of confidence in the answers.
    thanks for any input or suggestions,
    Geoff

    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One","Two","Three"};
        String[][] data = new String[40][3];
        for (int r=0; r<40; r++) {
          data[r] = new String[3];
          for (int c = 0; c < 3; c++) data[r][c] = "R" + r + "-C" + c;
        content.add(new JScrollPane(new JTable(data,head)));
        setSize(400, 400);
        show();
      public static void main(String args[]) { new Test(); }
    }I've been clicking until my fingers bled. Can't see a problem.

  • AS3 comboBox problem.

    Ok, I have a simple ComboBox with instance name of dragonCombo
    A Lable with an instance name of dragonLabel
    Using a an AS3 called Dragon.as
    When the ComboBox is clicked, a picture should pull up.   The problem is, there are no errors, but The ComboBox is not listing any of the Labels I loaded.  This is my AS3 code, maybe someone can see the mistake I have made somewhere.
    package
    import flash.display.MovieClip;
    import flash.display.Loader;
    import fl.controls.ComboBox;
    import fl.data.DataProvider;
    import flash.events.Event;
    import flash.text.TextFieldAutoSize;
    import flash.net.URLRequest;
    import flash.net.navigateToURL;
    import fl.controls.Label;
    public class Dragons extends MovieClip{
    public var dragonCombo:ComboBox;
    public var dragonLabel:Label;
    var comboDP:DataProvider;
    var dragonLoader:Loader;
    public function Dragons() {
    setupComboDP();
    setupdDragonCombo();
    setupLabels();
    private function setupComboDP():void{
    comboDP = new DataProvider();
    comboDP.addItem({ Label:"Fire"});
    comboDP.addItem({ Label:"IceNFire"});
    comboDP.addItem({ Label:"Ghost"});
    private function setupDragonCombo():void{
    dragonCombo.width = 150;
    dragonCombo.prompt = "Choose a Dragon";
    dragonCombo.dataProvider = comboDP;
    dragonLoader = new Loader();
    dragonLoader.x = 200.00;
    dragonLoader.y = 60.00;
    addChild(dragonLoader);
    dragonCombo.addEventListener(Event.CHANGE,loadData);
    public function setupLabels():void{
    dragonLabel.text="";
    dragonLabel.autoSize = dragonLabel.autoSize = TextFieldAutoSize.LEFT;
    public function loadData(e:Event):void{
    dragonLoader.load(new URLRequest("dragons3/"+e.target.selectedItem.Label.toLowerCase()+".png"));

    Your Dragons class is creating its own dragonCombo (it is not the one on the stage)...
           public var dragonCombo:ComboBox;
    that has no association with the combobox you placed on the stage manually as far as I can see.
    Assuming this is not your document class, if all you are doing is importing the Dragons class, then you are not implementing it at all.  You would have to have a line...
         var dragons:Dragons = new Dragons();
    in you fla in order to instantiate the class.  At that point you might start seeing error messages because in doing that your class is trying to target an object that doesn't exist because it only declared the combobox, it did not create an instance of it, as in...
          dragonCombo = new ComboBox();

  • Custom combobox problem

    Hi,
    With the help of JDC i am able to finish the work of creating the customized comobo but I'm stuck at the edge.
    I have a customized comobobox, which can show multiple columns in its combo popup, but only one item of column should be shown as selected in combo, This i achieved when combobox status is editable. but not working when combo is non editable.
    kindly see( can execute too ) the code and let me know where i'am going wrong.
    public class TestCoeusComboBox2 extends javax.swing.JFrame {
    /** Creates new form TestCoeusComboBox2 */
    public TestCoeusComboBox2() {
    initComponents();
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    //jPanel1.setLayout( new java.awt.GridLayout(2,4,10,10));
    jPanel1.setLayout( new java.awt.FlowLayout());
    java.util.Vector people = new java.util.Vector();
    for( int i= 0 ; i< 15 ; i++ ){           
    people.add(new ComboBoxBean(""+i,"Yaman kumar-"+i));
    javaEditable = new javax.swing.JLabel("java-Editable");
    javaNonEditable = new javax.swing.JLabel("java-NON Editable");
    coeusEditable = new javax.swing.JLabel("Coeus - Editable ");
    coeusNonEditable = new javax.swing.JLabel("Coeus - NON Editable");
    coeusComboEditable = new CoeusComboBox(people,true);
    coeusComboEditable.setPopupSelectionBackground(Color.yellow);
    coeusComboEditable.setPopupBackground(Color.white);
    coeusComboNonEditable = new CoeusComboBox(people,false);
    coeusComboNonEditable.setPopupSelectionBackground(Color.gray);
    coeusComboNonEditable.setPopupBackground(Color.white);
    javaComboEditable = new javax.swing.JComboBox(people);
    javaComboEditable.setEditable(true);
    javaComboNonEditable = new javax.swing.JComboBox(people);
    javaComboNonEditable.setEditable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jPanel1.setPreferredSize(new java.awt.Dimension(1000, 200));
    jPanel1.add(javaEditable); jPanel1.add(javaComboEditable);
    jPanel1.add(javaNonEditable); jPanel1.add(javaComboNonEditable);
    jPanel1.add(coeusEditable); jPanel1.add(coeusComboEditable);
    jPanel1.add(coeusNonEditable); jPanel1.add(coeusComboNonEditable);
    getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
    pack();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new TestCoeusComboBox2().show();
    private javax.swing.JPanel jPanel1;
    private CoeusComboBox coeusComboEditable;
    private CoeusComboBox coeusComboNonEditable;
    private javax.swing.JComboBox javaComboEditable;
    private javax.swing.JComboBox javaComboNonEditable;
    private javax.swing.JLabel javaEditable;
    private javax.swing.JLabel javaNonEditable;
    private javax.swing.JLabel coeusEditable;
    private javax.swing.JLabel coeusNonEditable;
    * @(#)CoeusComboBox.java 08/29/2002, 5:06 AM
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.event.*;
    import java.util.Vector;
    import javax.swing.border.*;
    public class CoeusComboBox extends JComboBox {
    private boolean editable = false;
    private Color popupSelBackground ;
    private Color popupBackGround;
    * Initializes the properties of CoeusComboBox as it needs to set custom Renderers
    * and Editors for CoeusComboBox
    private void initProperties(){       
    CoeusComboBoxRenderer renderer= new CoeusComboBoxRenderer();
    CoeusComboCellEditor editor = new CoeusComboCellEditor();
    setBorder(new LineBorder(Color.black,1));
    setRenderer(renderer);
    setEditor(editor);
    //setEditable(true);
    /** Creates a new instance of CoeusComboBox */
    public CoeusComboBox() {
    super();
    setUI(new StateComboBoxUI());
    initProperties();
    * Constructor with default ComboBoxModel
    public CoeusComboBox(ComboBoxModel aModel) {
    super(aModel);
    setUI(new StateComboBoxUI());
    initProperties();
    * Constructor with default items that are shown in popup when the combo is selected
    public CoeusComboBox(final Object[] items) {
    super(items);
    setUI(new StateComboBoxUI());
    initProperties();
    * Constructor with default items that are shown in popup when the combo is selected
    * @param items An array of elements that are shown in popup
    * @param editable Status of ComboBox, If true the combobox value can be modified.
    public CoeusComboBox(final Object[] items, boolean editable) {
    super( items);
    this.editable =editable;
    setEditable(editable);
    setUI(new StateComboBoxUI());
    initProperties();
    * Constructor with default items that are shown in popup when the combo is selected
    * @param items a Vector of combobox items.
    public CoeusComboBox(Vector items) {
    super(items);
    setUI(new StateComboBoxUI());
    initProperties();
    * Constructor with default items that are shown in popup when the combo is selected
    * @param items A vector of items that are shown in popup
    * @param editable Status of ComboBox, If true the combobox value can be modified.
    public CoeusComboBox(Vector items, boolean editable){
    super( items);
    this.editable = editable;
    setEditable(editable);
    setUI(new StateComboBoxUI());
    initProperties();
    * Sets combobox Popup Background Color
    * @param color background color of Combobox popup.
    public void setPopupBackground( Color color){
    this.popupBackGround = color;
    * Sets combobox Popup Selection Background Color
    * @param color Selected Item background color of Combobox popup.
    public void setPopupSelectionBackground( Color color){
    this.popupSelBackground = color;
    * Sets the Status(Editable/NonEditable) of combobox, Based on which the combo
    * value can be changed. Default is not editable
    * @param flag If true the combobox is editable.
    // public void setEditable( boolean flag){
    // editable = flag;
    * An inner class to set the Default renderer for CoeusComboBox. As this combobox
    * can show multiple columns in combo popup, so add number columns to this panel, like
    * that as many as number panel will be added to panel as many items available in combobox.
    * that is rendered in every cell.
    class CoeusComboBoxRenderer extends JPanel implements ListCellRenderer {
    private JLabel left;
    private JLabel right;
    private JLabel middle;
    * Constructor to set the layout and border for this panel.
    public CoeusComboBoxRenderer() {
    //setLayout(new GridLayout(1, 2,0,0));
    BoxLayout boxLayout =new BoxLayout(this,BoxLayout.X_AXIS);
    setLayout( boxLayout);
    setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
    left = new JLabel();
    middle= new JLabel();
    right = new JLabel();
    add(left);
    add(middle);
    add(right);
    * An overridden method to render this component in desired cell.
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (isSelected) {
    if(popupSelBackground == null ){
    popupSelBackground = list.getSelectionBackground();
    setBackground(popupSelBackground);
    setForeground(list.getSelectionForeground());
    } else {
    if( popupBackGround == null){
    popupBackGround = list.getBackground();
    setBackground(popupBackGround);
    setForeground(list.getForeground());
    if( value instanceof ComboBoxBean ){
    ComboBoxBean comboBoxBean = (ComboBoxBean) value;
    left.setText(comboBoxBean.getCode());
    middle.setText(" ");
    right.setText(comboBoxBean.getDescription());
    return this;
    }// end of CoeusComboBoxRenderer class
    * An inner class to set the editor of CoeusComboBox when it gets focus and about to be
    * selected by the user
    class CoeusComboCellEditor extends javax.swing.plaf.basic.BasicComboBoxEditor {
    public CoeusComboCellEditor() {
    super();
    System.out.println(" editable "+editable);
    editor.setEditable(true);
    //editor.setBackground(editorSelBackground);
    }// end of CoeusComboCellEditor
    }// end of CoeusComboBox
    * @(#)StateComboBoxUI.java 08/20/2002 9:21 AM
    import javax.swing.plaf.basic.*;
    import javax.swing.*;
    public class StateComboBoxUI extends BasicComboBoxUI{
    * Creates the ComboBox popup that is displayed when the implemented combobox is selected.
    * As in Basic LAF the combobox does not provide the horizontal scrollbar for popup this
    * method is overridden with that property.
    protected ComboPopup createPopup(){
    BasicComboPopup popup = new BasicComboPopup(comboBox){
    protected JScrollPane createScroller() {
    return new JScrollPane( list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );
    }//end of method createScroller
    return popup;
    }//end of method createPopup
    * The Class is used to populate any combo box
    public class ComboBoxBean implements java.io.Serializable{
    private String code;
    private String description="";
    /** Default Constructor */
    public ComboBoxBean() {
    /** Constructor with parameters */
         public ComboBoxBean(String code, String description) {
                   this.code = code;               this.description = description;
    * This method gets the Code
    * @return String code
    public String getCode() {
    return code;
    * This method sets the Code
    * @param String code
    public void setCode(String code) {
    this.code = code;
    * This method gets the Description
    * @return String description
    public String getDescription() {
    return description;
    * This method sets the Description
    * @param String description
    public void setDescription(String description) {
    this.description = description;
    public String toString(){
    return getDescription();

    Gregor,
              As an alternative way i did take "selectedItem" away from MXML and used it on "creationComplete". But not i am running in to different problem which i am going to open as new discussion.
    Between i have documented this issue on my blog @ http://www.srinivaskusunam.com/2009/05/13/flex-combobox-selecteditem-problem/
    Thanks,
    Srini

  • JTable rendering problem in JRE 1.6.0.10 under Linux

    I've encountered a bizarre issue using JTable. I've got a 3x10 JTable of Strings, values in which I change from within the program (no user input). After every update the value in the first column gets superimposed on the top of the previous one, so they are both visible, but totally unreadable (they interlace).
    I'm using Linux, and it only happens under jre 1.6.0.10. When I switch to 1.5.0.16 it works fine. I also noticed, that if I set the value to null in the first column and then set it to the new value it works fine. However, if I do it simply like that:
    table.setValueAt(null, 1, 0);
    table.setValueAt(newValue, 1, 0);it doesn't work. I need to re-set it to null on one user's click (it triggers the update) and only change it on the following click. Am I reporting a bug here, or is it a known issue with some proper solution?
    Thanks

    There are some crazy things, I can't explain...
    1) Here is my [sample project|http://vlkv.storm-soft.kiev.ua/_mywiki/images/6/6f/JavaApplication1.tar.gz]. I've created it with NetBeans 6.5 and jdk 1.6.0_11.
    2) there are directories dist_windows, dist_linux with jars, created under Windows and Linux (same version JDK everywhere). You may compare both JavaApplication1.jar files with some diff tool (such as WinMerge) and you can see that these jars are slightly different. WHY?
    3) Run my sample
    java -jar JavaApplication1.jarpress the button and scroll up and down JTable. Under Windows everything is ok. But under Linux I have the subj bug with BOTH dist_windows/JavaApplication1.jar and dist_linux/JavaApplication1.jar !!!
    4) Start NetBeans 6.5 and open the project. Run the project from inside NetBeans on Linux. Then I see that my java program runs perfectly, without any bugs!!!
    This command
    ps fu -C javaproduces this output:
    vlkv 8778 1.0 2.8 217084 22408 ? Sl 14:01 0:00 \_ /usr/java/jdk1.6.0_11/bin/java -classpath /home/vlkv/NetBeansProjects/JavaApplication1/build/classes:/home/vlkv/NetBeansProjects/JavaApplication1/src NewJFrame
    But if I run NewJFrame without NetBeans like this (copy/paste command):
    /usr/java/jdk1.6.0_11/bin/java -classpath /home/vlkv/NetBeansProjects/JavaApplication1/build/classes:/home/vlkv/NetBeansProjects/JavaApplication1/src NewJFrame
    This bug returns!!! WHY UNDER NETBEANS IT'S OKAY?
    Where are the java experts to help us, please?
    PS: I've found a topic about this problem, unfortunately not answered, here .

  • JTable + combobox

    Hi,
    I'm new with JTable.
    I've a JTable where I added a comboBox.
    I need to open a Dialog box by selecting an option from the comboBox.
    Please let me know how can I do that...
    thanks in advance.
    here is how I added my combobox
    code
              //Set up the editor for the cells.
              JComboBox comboBox = new JComboBox(items);
              column.setCellEditor(new DefaultCellEditor(comboBox));
              //DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              ComboBoxRenderer renderer = new ComboBoxRenderer(items);
              column.setCellRenderer(renderer);
    code
    Edited by: user1202074 on Aug 4, 2011 10:14 AM
    Edited by: user1202074 on Aug 4, 2011 10:25 AM

    Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.
    Then edit your post and format the code correctly.

Maybe you are looking for

  • My 32G ipod touch is stuck in recovery mode. Is there anyway I can recover music and photographs? I do not have the old laptop. :(

    Hello there! I just recently tried updating my 32G ipod touch. Low and behold it incurs a problem and my ipod is now stuck in recovery mode. Is there anyway I can retrieve the music and photographs. PLEASE HELP!

  • Oracle 9i install problem on Redhat 7.1

    Hi there, I have some problems during the installation of Oracle 9i on RedHat 7.1: All is ok untill the install of "linking Oracle 9i installation" by this time it runs some makefiles to link and install files. It requires a library called libclntsh

  • Error message stating I need to authorize the computer

    No matter how many times I have authorized this computer, I continue to receive the Error message stating I need to authorize the computer. I have authorized the computer over and over and still it will not sync. In addition, the Apps shows I have ap

  • Questions about Mapping GL Accounts to Group Accounts

    Hi, I have some questions about mapping gl accounts to group accounts while configuring OBIEE APPS 7.9.6.3 with EBS R12 as a source: FIRST QUESTION.- For file file_group_acct_codes_ora.csv, I have the following accounts from my customer: 101101 - Caj

  • ERROR FRM-92100

    sir i frequently get the following error on client machine "FRM-92100 your connection to the server is interrupted this may be the result of network error or a failure on the server you need to reestablish your session" pls guide what may be the reas