JTable in JInternalFrame

Hi,
I am having a problem with editing cells in a JTable. I have initially created a table using a custom table model in a JFrame. Everything works as expected.
Now that I have modified it so that the JFrame becomes a JInternalFrame inside my Desktop I have lost the ability to edit cells.
I can still select individual cells, however no caret displays and no input from the keyboard is accepted.
I don't understand why the ability to edit cells is lost whenever the table is in a JInternalFrame.
Could someone explain or suggest why this would be happening.
Thanks.

Hi,
Thanks for the quick reply.
I tried them both but it didn't work and Yes everything is set to use a JDesktopPane.
below is some of the code if that helps
//This is the AbstractTableModel
class MatrixTableModel extends AbstractTableModel
  private double[][] data = { {0.0} };
  public int getColumnCount()
    return data.length;
  public int getRowCount()
   return data.length;
   public Object getValueAt(int row, int col)
    return new Double(data[row][col]);     
   public boolean isCellEditable(int row, int col)
     return true;     
   public void setValueAt(Object value, int row, int col)
    double doubleVal;
    try
     doubleVal = new Double(value.toString()).doubleValue();       
     data[row][col] = Math.floor(doubleVal*1000 + .5) /1000;
     fireTableCellUpdated(row,col);
     fireTableCellUpdated(col,row);
    catch (NumberFormatException e)
      JOptionPane.showMessageDialog(null,"Input matrix can only contain real values");
   public void changeData(double A[][])
    data = A;
    mtm.fireTableStructureChanged();
//The TableColumnModel I use
TableColumnModel cm = new DefaultTableColumnModel()
public void addColumn(TableColumn tc)
  tc.setMinWidth(50);
  tc.setMaxWidth(100);    
  seqEditor = new JTextField();     
  seqEditor.setMargin(new Insets(0,0,0,0));
  seqEditor.setHorizontalAlignment(SwingConstants.CENTER);
  seqCellEditor = new DefaultCellEditor(seqEditor);
  seqCellEditor.setClickCountToStart(1);
  tc.setCellEditor(seqCellEditor);
  super.addColumn(tc);
//each are added as follows
    Matrix = new JTable(mtm);
    Matrix.setColumnModel(cm); The cells look as if they are selected - i.e. the rectangle outline is black when selected.
I placed a message in the setValueAt method and i know that it is called whenever i select away from a selectd cell.
Any ideas,
Thanks

Similar Messages

  • Problem in refreshing jinternalframe

    Hello,
    In java code I have added jtable to jinternalframe and
    on each button click I have to show new values filled in jtable which is in jinternalframe.But I am getting new jinternalframe next to original jinternalframe.I want new jinternalframe to be superimposed on previous.What is solution to this?
    code:
    buttonNext.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    System.out.println("rowno"+tableActual.getRowCount());
    if(i<tableActual.getRowCount())
    String s1=tableActual.getValueAt(i,1).toString();
    System.out.println("s1:"+s1);
    tableVirtual.table.setValueAt(s1,i,1);
    System.out.println("s1 in vtable:"+tableVirtual.table.getValueAt(i,1));
    stepLabel.setText("Calculating Gen"+tableVirtual.table.getValueAt(i,1));
    String s2=tableActual.getValueAt(i,2).toString();
    tableVirtual.table.setValueAt(s2,i,2);
    stepLabel.setText("Calculating Kill"+tableVirtual.table.getValueAt(i,1));
    i=i+1;
    System.out.println("i="+i);
    tableVirtual.showTable();
    desktop.remove(frame);
    JInternalFrame frame = new JInternalFrame("SimpleTableDemo",true,true,true,true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tableVirtual.setOpaque(true); //content panes must be opaque
    frame.setContentPane(tableVirtual);
    //Display the window.
    frame.pack();
    frame.setLocation(0,451);
    frame.setVisible(true);
    desktop.add(frame);
    });

    I have tried it. But its giving next internal frame of half size than previous one.
    And new jinternalframe is still in background of previous one.What to do to take it to front?I have tried jinternalframe.front().But it has no effect.

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

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

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

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** 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() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • JInternalFrame  , Jtable && XML

    Hi all ,
    I am trying to Build a GUI program that gets the data from the XML file and then put it into the Jtable . The jtable is in the Jinternalframe .
    When I try to add one Jinternalframe that containing the Jtable , it works fine .
    But when I try to put the other Jinternalframe that containing another Jtable .
    It fails . I can compile the program but can't run it .
    It is the error code :
    Exception in thread "main" java.lang.NullPointerException
    at tablemodel.getColumnName(tablemodel.java:92)
    at TableMap.getColumnName(TableMap.java:38)
    at javax.swing.JTable.addColumn(JTable.java:1841)
    at javax.swing.JTable.createDefaultColumnsFromModel(JTable.java:927)
    at javax.swing.JTable.tableChanged(JTable.java:2842)
    at javax.swing.JTable.setModel(JTable.java:2710)
    at javax.swing.JTable.<init>(JTable.java:357)
    at javax.swing.JTable.<init>(JTable.java:297)
    at jin_frame.<init>(jin_frame.java:15)
    at button.<init>(button.java:41)
    at button.main(button.java:115)
    Can somebody help ??

    Could you show the code that you used to do this? I am trying to do the same thing. Thank you.

  • JTable wont refresh in JInternalFrame

    hello people
    my JTable wont refresh when iam using the form as an JInternalFrame, but if i use it as JFrame then the table will refresh, here is a bit of my code
    public void getTable()
              Statement sat;
              ResultSet rs;
              try {
                   int idx = queryType.getSelectedIndex();
                   String s = columnNames[idx];
                   JOptionPane.showMessageDialog(null, "yeah "+s);
                   String query = "SELECT * FROM College_Master " +
                                       " WHERE  ("+s+") ='" + typelist.getSelectedItem()+"'";
                   sat = connection.createStatement();
                   rs = sat.executeQuery(query);
                   displayResultSet(rs);
                   sat.close();
              catch(SQLException sqlex) {
                   sqlex.printStackTrace();
         public void displayResultSet (ResultSet rs)
                   throws SQLException
                   boolean moreRecords = rs.next();
                   if(! moreRecords){
                        JOptionPane.showMessageDialog(this, "No record to display. Please query again.");
                        setTitle("No records to dispaly");
                        return;
                   Vector columnHeads = new Vector();
                   Vector rows = new Vector();
                   try {
                        ResultSetMetaData rsmd = rs.getMetaData();
                        for(int i = 1;i<=rsmd.getColumnCount();i++)
                        columnHeads.addElement(rsmd.getColumnName(i));
                   do {
                             ctr2++;
                             rows.addElement (getNextRow(rs, rsmd));
                             JOptionPane.showMessageDialog(null, "here"+ctr2);
                        } while (rs.next());
                        table = new JTable(rows, columnHeads);
                        JScrollPane scroller = new JScrollPane(table);
                        scroller.setBounds(10,40,660,250);
                        c.add(scroller);//c is a panel
                        validate();
                   catch(SQLException sqlex) {
                        sqlex.printStackTrace();
         public Vector getNextRow (ResultSet rs, ResultSetMetaData rsmd)
                             throws SQLException
                   Vector currentRow = new Vector();
                   for (int i=1;i<=rsmd.getColumnCount();i++)
                   switch(rsmd.getColumnType(i)) {
                        case Types.VARCHAR:
                             currentRow.addElement (rs.getString(i));
                             break;
                        case Types.INTEGER:
                             currentRow.addElement(new Long(rs.getLong(i)));
                             break;
                        default:
                             System.out.println("Type was: " + rsmd.getColumnTypeName(i));
                   return currentRow;
              }whats wrong?
    asrar

    hello people
    my JTable wont refresh when iam using the form as an JInternalFrame, but if i use it as JFrame then the table will refresh, here is a bit of my code
    public void getTable()
              Statement sat;
              ResultSet rs;
              try {
                   int idx = queryType.getSelectedIndex();
                   String s = columnNames[idx];
                   JOptionPane.showMessageDialog(null, "yeah "+s);
                   String query = "SELECT * FROM College_Master " +
                                       " WHERE  ("+s+") ='" + typelist.getSelectedItem()+"'";
                   sat = connection.createStatement();
                   rs = sat.executeQuery(query);
                   displayResultSet(rs);
                   sat.close();
              catch(SQLException sqlex) {
                   sqlex.printStackTrace();
         public void displayResultSet (ResultSet rs)
                   throws SQLException
                   boolean moreRecords = rs.next();
                   if(! moreRecords){
                        JOptionPane.showMessageDialog(this, "No record to display. Please query again.");
                        setTitle("No records to dispaly");
                        return;
                   Vector columnHeads = new Vector();
                   Vector rows = new Vector();
                   try {
                        ResultSetMetaData rsmd = rs.getMetaData();
                        for(int i = 1;i<=rsmd.getColumnCount();i++)
                        columnHeads.addElement(rsmd.getColumnName(i));
                   do {
                             ctr2++;
                             rows.addElement (getNextRow(rs, rsmd));
                             JOptionPane.showMessageDialog(null, "here"+ctr2);
                        } while (rs.next());
                        table = new JTable(rows, columnHeads);
                        JScrollPane scroller = new JScrollPane(table);
                        scroller.setBounds(10,40,660,250);
                        c.add(scroller);//c is a panel
                        validate();
                   catch(SQLException sqlex) {
                        sqlex.printStackTrace();
         public Vector getNextRow (ResultSet rs, ResultSetMetaData rsmd)
                             throws SQLException
                   Vector currentRow = new Vector();
                   for (int i=1;i<=rsmd.getColumnCount();i++)
                   switch(rsmd.getColumnType(i)) {
                        case Types.VARCHAR:
                             currentRow.addElement (rs.getString(i));
                             break;
                        case Types.INTEGER:
                             currentRow.addElement(new Long(rs.getLong(i)));
                             break;
                        default:
                             System.out.println("Type was: " + rsmd.getColumnTypeName(i));
                   return currentRow;
              }whats wrong?
    asrar

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

  • Retrieving values entered in a JTable

    Hi!
    I have made a sudoku solver as many others, but in the purpose of learning recursion, and now I am implementing GUI to that program. I have bean strugling to set up a table that shows the sudokutable, and most of all how to recieve the values entered into the table. I have looked at forums and search at google, but all the topics on this is not good enough. I just simply do not understand what they mean. Most often they just say: "Just paste this code in and it will turn out as intended". I want to know how it works.
    I have added the code below:
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.*;
    import java.awt.event.*;
    import easyIO.*;
    import java.util.*;
    import java.io.*;
    * Klassen Oblig3 som inneholder main metoden som starter programmet.
    * Dette er Utsynen for programmet.
    * @Param ru - Peker til klassen Rute.
    * @Param br - Peker til klassen Brett.
    * @Param skrivebord - En ny desktpoPane som representerer hovedvinduet..
    public class Oblig3 extends JFrame implements ActionListener {
         Rute  ru   = new Rute();
         Brett br   = new Brett(ru);
         ImageIcon icon;
         Image image;
         JDesktopPane skrivebord;
          * Konstrukt�ren Oblig3 som setter opp hovedvinduet.
          * @Param skjemrStorelse - Lagrer st�relsen p� skjermen.
         public Oblig3() {
              super("Oblig3");
              int innrykk = 400;
              Dimension skjermStorelse = Toolkit.getDefaultToolkit().getScreenSize();
              setBounds(innrykk, innrykk, skjermStorelse.width  - innrykk*3, skjermStorelse.height - innrykk*2);
              skrivebord = new JDesktopPane()
                   Image im = (new ImageIcon("bilder/panzer.gif")).getImage();
                   public void paintComponent(Graphics g){
                        g.drawImage(im,0,0,this);
              setContentPane(skrivebord);
              setJMenuBar(lagMenyList());
              skrivebord.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
         } // Slutt p� konstrukt�ren Oblig3
         * JMenuBar metoden som gir menyen til hovedvinduet.
         * @Param menyList - Peker p� et MenuBar objekt.
         * @Param meny# - Menyene p� menylisten.
         * @Param menyObjekt - Et valg p� gitt meny.
         protected JMenuBar lagMenyList() {
              JMenuBar menyList = new JMenuBar();
              // F�rste menyen
              JMenu meny1 = new JMenu("Fil");
              meny1.setMnemonic(KeyEvent.VK_F);
              menyList.add(meny1);
                   // Gruppe1 med JMenuObjekt
                   JMenuItem menyObjekt = new JMenuItem("�pne brett", new ImageIcon("bilder/folder.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_O);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("�pne brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   menyObjekt = new JMenuItem("Spare brett", new ImageIcon("bilder/floppy.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_S);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Spare brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   meny1.addSeparator();
                   menyObjekt = new JMenuItem("Exit");
                   menyObjekt.setMnemonic(KeyEvent.VK_ESCAPE);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Exit");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
              // Lage den andre menyen
              JMenu meny2 = new JMenu("Edit");
              meny1.setMnemonic(KeyEvent.VK_E);
              menyList.add(meny2);
                   // Gruppe2 med JMenObjekt
                   menyObjekt = new JMenuItem("L�s Brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("L�s Brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
                   menyObjekt = new JMenuItem("Lag eget brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));
                   menyObjekt.setActionCommand("Lag eget brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
              // Lage den tredje menyen
              JMenu meny3 = new JMenu("Hjelp");
              meny1.setMnemonic(KeyEvent.VK_H);
              menyList.add(meny3);
                   // Gruppe3 med JMenObjekt
                   menyObjekt = new JMenuItem("Version?");
                   menyObjekt.setActionCommand("Version?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
                   menyObjekt = new JMenuItem("www.dresas.com");
                   menyObjekt.setActionCommand("www.dresas.com?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
              return menyList;
         } // Slutt p� JMenuBar metoden.
         * Metode som lytter p� menyval mm.
         public void actionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals("�pne brett")) {
                   lesFraFil();
              } else if (e.getActionCommand().equals("L�s Brett")) {
                   losning();
              } else if (e.getActionCommand().equals("Exit")) {
                   System.exit(0);
              } else if (e.getActionCommand().equals("Version?")) {
                   version();
              } else if (e.getActionCommand().equals("www.dresas.com")) {
                   link();
              } else if (e.getActionCommand().equals("Lag eget brett")) {
                   lagEgetBrett();
              } // Slutt p� if-else-if setning.
         * Metoden lesFraFil som ber om navn p� fil fra bruker
         * via grensesnittet.
         protected void lesFraFil() {
              final String losFraFil = JOptionPane.showInputDialog(null, "Skriv inn navn p� filen.");
              svarLesFraFil(losFraFil + ".txt");
         } // Slutt p� metoden losFraFil
         * Metoden svarLesFaFil som gir resultat p� inlesning fra fil.
         protected void svarLesFraFil(String filnavn) {
              boolean rF = br.lesBrettFraFil(filnavn);
              if(rF == true) {
                    JOptionPane.showMessageDialog(this, "Filen er lest inn");
              } else {
                    JOptionPane.showMessageDialog(this, "Filen ble ikke lest inn,\n (husk sm� og store bokstaver)");
              } // Slutt p� if-else
         } // Slutt p� metoden svarLosFraFil
         * Metoden losning som gir resultat p� l�st brett.
         protected void losning() {
              ru.provAlleSifferMegOgResten(0);
              br.skrivLosning();
         } // Slutt p� metoden losning
         protected void version() {
              JOptionPane.showMessageDialog(null, "Dette er version 0.7");
         protected void link() {
              OpenBrowser op = new OpenBrowser();
              op.displayURL("www.dresas.com");
         } // Slutt p� metoden link
         * Metoden lagEgetBrett som lar brukeren tegne sitt eget
         * brett og l�se det.
         * @Param ramme - Peker p� objektet av klassen InternRamme som
         *                setter opp det interne vinduet.
         protected void lagEgetBrett() {
              int boksBredde = 3;
              int boksHojde  = 3;
              int brettStorelse = 9;
              boolean b1 = true;
              while (b1) {
                   boksBredde = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn Bredde p� boksen. (2-4)"));
                   if (boksBredde > 1 && boksBredde < 5) {
                        boksHojde  = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn H�jde p� boksen. (3-4)"));
                        if (boksHojde > 2 && boksHojde < 5) {
                             b1 = false;
                        } else {
                             JOptionPane.showMessageDialog(null, "M� vaere mellom 3 og 4.");
                             continue;
                   } else {
                        JOptionPane.showMessageDialog(null, "M� vaere mellom 2 og 4.");
                        continue;
              brettStorelse = boksBredde * boksHojde;
              InternRamme ramme = new InternRamme(brettStorelse * 16, brettStorelse * 16);
                   Object[][] data = new Object[brettStorelse][brettStorelse];
                   for (int i = 0;i < brettStorelse;i++) {
                        for (int j = 0; j < brettStorelse;j++) {
                             data[i][j] = 0;
                   String[] columnNames = new String[brettStorelse];
                   for (int i = 0; i < brettStorelse;i++) {
                        int b = 1 + i;
                        columnNames[i] = String.valueOf(b);
                   JTable sudokuTabell = new JTable(data, columnNames);
                   sudokuTabell.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
                   sudokuTabell.setFont(new Font ("Tahoma", Font.PLAIN, 16));
                   setVisible(true);
              ramme.add(sudokuTabell);
              ramme.setVisible(true);
              skrivebord.add(ramme);
              try {
                   ramme.setSelected(true);
              } catch (java.beans.PropertyVetoException e) {}
         } // Slutt p� klassen lagEgetBrett
         * Metode som returnerer tilfeldigt verdi st�rre en 0 og mindre
         * en maks.
         public static int tilfeldig (int maks) {
              return (int) (Math.random () * maks);
        * Metoden utsyn som tegner opp programmet p� skjermen.
        * @Param frame - Peker p� objektet Oblig3.
        private static void utsyn() {
            //Create and set up the window.
            Oblig3 frame = new Oblig3();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
        } // Slutt p� metoden utsyn.
        * Metoden main som starter programmet.
        public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    utsyn();
         } //  Slutt p� metoden main.
    } // Slutt p� klassen Oblig3.
    * Brukt av Oblig3
    class InternRamme extends JInternalFrame {
         static int tellOpneRammer = 0;
         static final int xOffset = 30, yOffset = 30;
         InternRamme(int bredde, int hojde) {
              super("Lag eget Brett #" + (++tellOpneRammer),
                     true, //resizable
                     true, //closable
                     true, //maximizable
                     true);//iconifiable
              //...Create the GUI and put it in the window...
              //...Then set the window size or call pack...
              setSize(bredde,hojde);
              //Set the window's location.
              setLocation(xOffset*tellOpneRammer, yOffset*tellOpneRammer);
    }

    Here is the method in mind, translated...
    protected void ConstructOwnBoard() {
         int boxWidth = 3;
         int boxHeight = 3;
         int BoardSize = 9;
         boolean b1 = true;
         while (b1) {
              boxWidth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Width. (2-4)"));
              if (boxWidth > 1 && boxWidth < 5) {
                   boxHeight = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Height. (3-4)"));
                   if (boxHeight > 2 && boxHeight < 5) {
                        b1 = false;
                   } else {
                        JOptionPane.showMessageDialog(null, "Must be btween 3 og 4.");
                        continue;
              } else {
                   JOptionPane.showMessageDialog(null, "Must be between 2 og 4.");
                   continue;
         BoardSize = boxWidth * boxHeight ;
         InternalFrame frame = new InternalFrame(BoardSize * 16, BoardSize * 16);
         Object[][] data = new Object[BoardSize ][BoardSize ];
         for (int i = 0;i < BoardSize ;i++) {
              for (int j = 0; j < BoardSize ;j++) {
                   data[i][j] = 0;
         String[] columnNames = new String[BoardSize ];
         for (int i = 0; i < BoardSize ;i++) {
              int b = 1 + i;
              columnNames[i] = String.valueOf(b);
         JTable sudokuTable = new JTable(data, columnNames);
         sudokuTable.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
         sudokuTable.setFont(new Font ("Tahoma", Font.PLAIN, 24));
         TableColumn column = null;
         for (int i = 0; i < BoardSize ; i++) {
              column = sudokuTable.getColumnModel().getColumn(i);
              column.setMinWidth(25);
              column.setMaxWidth(25);
              column.setResizable(false);
         setVisible(true);
         frame.add(sudokuTable);
         frame.setVisible(true);
         desktop.add(ramme);
         try {
              frame.setSelected(true);
         } catch (java.beans.PropertyVetoException e) {}
    } // end of class

  • How to edit databases from JTable?

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
    I have the installer of an application which I made with Java SE called FuelStation.exe
    My class files are ready for sharing along with its source files.
    I have placed it in this location in my website:
    http://www.apachevista.com/alphaprojects/runfiles/
    It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
    Here is my sample code:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
    // JDBC driver, database URL, username and password
    ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
    final String JDBC_DRIVER = bundle.getString("Driver");
    final String DATABASE_URL = bundle.getString("URL");
    final String USERNAME = bundle.getString("User");
    final String PASSWORD = bundle.getString("Password");
    // default query retrieves all data from authors table
    //static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
    final String DEFAULT_QUERY = bundle.getString("Query");
    private ResultSetTableModel tableModel;
    private JTextArea queryArea;
    static final int xOffset = 0, yOffset = 200;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
    // create ResultSetTableModel and GUI
    public DisplayQueryResults() {  
    super("Sales of the Day",
    true, //resizable
    true, //closable
    true, //maximizable
    false);//iconifiable
    //...Create the GUI and put it in the window...
    //Set the window's location.
    setLocation(xOffset, yOffset);
    // create ResultSetTableModel and display database table
    try {
    // create TableModel for results of query SELECT * FROM authors
    tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
    USERNAME, PASSWORD, DEFAULT_QUERY);
    // set up JTextArea in which user types queries
    queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
    queryArea.setWrapStyleWord(true);
    queryArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(queryArea,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    // set up JButton for submitting queries
    JButton submitButton = new JButton("Submit Query");
    // create Box to manage placement of queryArea and
    // submitButton in GUI
    Box box = Box.createHorizontalBox();
    box.add(scrollPane);
    box.add(submitButton);
    // create JTable delegate for tableModel
    JTable resultTable = new JTable(tableModel);
    resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
    resultTable.setRowSelectionAllowed(true);
    resultTable.getModel().addTableModelListener(this); // step 3
    // place GUI components on content pane
    add(box, BorderLayout.NORTH);
    add(new JScrollPane(resultTable), BorderLayout.CENTER);
    // create event listener for submitButton
    submitButton.addActionListener(
    new ActionListener()
    // pass query to table model
    public void actionPerformed(ActionEvent event)
    // perform a new query
    try
    tableModel.setQuery(queryArea.getText());
    } // end try
    catch ( SQLException sqlException)
    JOptionPane.showMessageDialog(null,
    sqlException.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // try to recover from invalid user query
    // by executing default query
    try {
    tableModel.setQuery(DEFAULT_QUERY);
    queryArea.setText(DEFAULT_QUERY);
    } // end try
    catch (SQLException sqlException2) {
    JOptionPane.showMessageDialog(null,
    sqlException2.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end inner catch
    } // end outer catch
    } // end actionPerformed
    } // end ActionListener inner class
    ); // end call to addActionListener
    //...Then set the window size or call pack...
         setSize(750,300);
    setVisible(true); // display window
    } // end try
    catch (ClassNotFoundException classNotFound) {
    JOptionPane.showMessageDialog(null,
    "MySQL driver not found", "Driver not found",
    JOptionPane.ERROR_MESSAGE);
    System.exit(1); // terminate application
    } // end catch
    catch (SQLException sqlException) {
    JOptionPane.showMessageDialog(null, sqlException.getMessage(),
    "Database error", JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end catch
    // dispose of window when user quits application (this overrides
    // the default of HIDE_ON_CLOSE)
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    // ensure database connection is closed when user quits application
    addInternalFrameListener(
    new InternalFrameAdapter() {
    // disconnect from database and exit when window has closed
    public void windowClosed(WindowEvent event) {
    tableModel.disconnectFromDatabase();
    System.exit(0);
    } // end method windowClosed
    } // end WindowAdapter inner class
    ); // end call to addWindowListener
    } // end DisplayQueryResults constructor
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    // execute application
    public static void main(String args[]) {
    new DisplayQueryResults();
    } // end main
    } // end class DisplayQueryResults
    My question is in lines 177-187:
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
    If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
    PS:
    When you have solved the problem, please notify me with the code that's changed
    and please share it to others if you like so.
    Best Wishes: Oliver Bob Lagumen
    Email: [email protected]
    website: www.apachevista.com
    Oliver Bob Lagumen
    Edited by: Oliverbob on Jan 24, 2008 9:03 PM

    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?What does happen when you click on the cells?
    Does the ResultSetTableModel report the cells as editable? If not you will never get to edit their contents, and so the table's model won't change, and so the table model listener will never get invoked.
    When you post code here use the code tags. Basically you put {code} at the start of your code and again at the end. That way the code will be readable.
    Try to post minimal examples with which others can reproduce your problem. In this case "minimal" would involve removing or drastically simplifying a lot of the GUI stuff which is just noise. But "reproduce" would involve including the ResultSetTableModel.
    When you have solved the problem, please notify me with the code that's changedAvoid this.
    What you say here is quite possibly not what you mean. But, in any event, while there might be plenty of interest in helping with specific problems there will likely be none in writing your code. Your problem remains yours. But your solution and your code - prompted by whatever help you might recieve - will also be yours.

  • JPopupMenu with JInternalFrame, popup menu doesn't work

    hi, i have this problem, as shown in the sample code at the end of this post.. basically, i have a table, and i added a JPopupMenu onto the table.. the popup menu works well when running the table class, though, when i call the table class in a JInternalFrame environment, the popup menu won't work.. anyone know why?
    ///Basic sample table code, when run this alone, the popup menu will work
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableBasic extends JPanel
         private JTable table;
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        { new Date(), "B", new Integer(2), Boolean.FALSE },
                        { new Date(), "C", new Integer(9), Boolean.TRUE },
                        { new Date(), "D", new Integer(4), Boolean.FALSE}
              table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public void createPopupMenu()
              JMenuItem menuItem;
              //Create the popup menu.
              JPopupMenu popup = new JPopupMenu();
              menuItem = new JMenuItem("A popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              menuItem = new JMenuItem("Another popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              //Add listener to the text area so the popup menu can come up.
              MouseListener popupListener = new PopupListener(popup);
              table.addMouseListener(popupListener);
         public static void main(String[] args)
              JFrame frame = new JFrame();
              TableBasic table = new TableBasic();
              table.createPopupMenu();
              frame.setContentPane(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         class PopupListener extends MouseAdapter
              JPopupMenu popup;
              PopupListener(JPopupMenu popupMenu)
                   popup = popupMenu;
              public void mousePressed(MouseEvent e)
                   maybeShowPopup(e);
              public void mouseReleased(MouseEvent e)
                   maybeShowPopup(e);
              private void maybeShowPopup(MouseEvent e)
                   if (e.isPopupTrigger())
                        popup.show(e.getComponent(), e.getX(), e.getY());
    ///when integrate the previous table into here, popup menu won't work
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameBasic
         extends JFrame
         //implements ActionListener
         private JDesktopPane desktop;
         private JInternalFrame menuWindow;
         public static final int desktopWidth = 800;
         public static final int desktopHeight = 700;
         public InternalFrameBasic(String title)
              super(title);
              //Set up the GUI.
              desktop = new JDesktopPane();
              desktop.putClientProperty("JDesktopPane.dragMode", "outline");
              //Because we use pack, it's not enough to call setSize.
              //We must set the desktop's preferred size.
              desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
              setContentPane(desktop);
              createMenuWindow();
              desktop.add(menuWindow); //DON'T FORGET THIS!!!
              Dimension displaySize = menuWindow.getSize();
              menuWindow.setSize(desktopWidth, displaySize.height);
         private void createMenuWindow()
              menuWindow =
                             new JInternalFrame("Event Watcher", true, //resizable
                                                                                                   true, //closable
                                                                                                   false, //not maximizable
                                                                                                   true); //iconifiable
              menuWindow.setContentPane(new TableBasic());
              menuWindow.pack();
              menuWindow.setVisible(true);
          * 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 InternalFrameBasic("Example Internal Frame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //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();
    }

    table.createPopupMenu();The above line should not be in the main method. It should be in the constructor class of TableBasic.
    You never execute that method in your InternalFrameBasic class to the mouse listener never gets added to the table.

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • JCheckBox wont receive initial focus in JTable under 1.6

    If I have a JCheckBox in a JTable, clicking the checkbox has no effect unless the table already has focus. This is new to 1.6 I believe.
    The code example below should illustrate the problem. With focus on the JTextField at the top, try to click a checkbox in the table. It won't take respond. If you click another field in the table first, the checkbox will then begin responding. Two strange things I've noticed with it are.
    1) removing the call the table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); makes it work correctly. Of course then it won't give up focus correctly.
    2) My example has the JTable within a JInternalFrame. If the table is just in a JFrame, the problem disappears. You can commment/uncomment these two lines to see the difference:
    initInteralFrame(panel);
    //initNoInteralFrame(panel);
    I'm very surprised nobody else has noticed this, but I didn't see any postings or bugs on it. Can anyone see something I am doing wrong or find a workaround?
    I submitted this bug a while back which is probably related, but this case with the checkbox is a bit less obscure:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6568959
    import java.awt.Dimension;
    import javax.swing.BoxLayout;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    public class TableTest2 extends JFrame
         public TableTest2()
              addWindowListener(new java.awt.event.WindowAdapter()
                   public void windowClosing(java.awt.event.WindowEvent evt)
                        System.exit(0);
              JPanel panel = new JPanel();
              panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
              String[] columnNames = {"First Name",     "Last Name","Sport","# of Years","Vegetarian"};
              //Object[][] data= new Object[3][5];
              Object[][] data = {
                   {"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
                   {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
                   {"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
                   {"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
                   {"Philip", "Milne","Pool", new Integer(10), new Boolean(false)}
              DefaultTableModel myModel = new DefaultTableModel(data, columnNames)
                   public Class getColumnClass(int c)
                        return getValueAt(0, c).getClass();
              JTable table = new JTable(myModel);
              table.setSurrendersFocusOnKeystroke(true);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              JScrollPane jScrollPane = new JScrollPane();
              jScrollPane.setViewportView(table);
              panel.add(new JLabel("Field 1"));
              panel.add(new JTextField(15));
              panel.add(jScrollPane);
              // ************ comment out one or the other of these to see error
              initInteralFrame(panel);
              //initNoInteralFrame(panel);
              Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
              setSize(new Dimension(800, 600));
              setLocation((screenSize.width-800)/2,(screenSize.height-600)/2);
         private void initInteralFrame(JPanel panel)
              JInternalFrame jif = new JInternalFrame();
              JDesktopPane desktop = new JDesktopPane();
              jif.setVisible(true);
              desktop.add(jif);
              setContentPane(desktop);
              jif.add(panel);
              jif.pack();
         private void initNoInteralFrame(JPanel panel)
              getContentPane().add(panel);
          * @param args the command line arguments
         public static void main(String args[])
              new TableTest2().setVisible(true);
    }

    It appears to me that the first click is "selecting"
    the internal frame to make it active and therefore
    have focus.Under 1.5, that appears to be the behavior. Under 1.6 the focus starts out in the internal frame on the JTextField above the JTable. You can click into any field in the table from there fine, but you can't transfer focus from the JTextField outside the table to the JCheckbox in the table... no matter how many clicks. The checkbox only works after the table becomes focused by clicking on one of the other fields or tabbing into the table.

  • Editing MySQL Database from JTable

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
    I have the installer of an application which I made with Java SE called FuelStation.exe
    My class files are ready for sharing along with its source files.
    I have placed it in this location in my website:
    http://www.apachevista.com/alphaprojects/runfiles/
    It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
    Here is my sample code:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
    // JDBC driver, database URL, username and password
    ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
    final String JDBC_DRIVER = bundle.getString("Driver");
    final String DATABASE_URL = bundle.getString("URL");
    final String USERNAME = bundle.getString("User");
    final String PASSWORD = bundle.getString("Password");
    // default query retrieves all data from authors table
    //static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
    final String DEFAULT_QUERY = bundle.getString("Query");
    private ResultSetTableModel tableModel;
    private JTextArea queryArea;
    static final int xOffset = 0, yOffset = 200;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
    // create ResultSetTableModel and GUI
    public DisplayQueryResults() {  
    super("Sales of the Day",
    true, //resizable
    true, //closable
    true, //maximizable
    false);//iconifiable
    //...Create the GUI and put it in the window...
    //Set the window's location.
    setLocation(xOffset, yOffset);
    // create ResultSetTableModel and display database table
    try {
    // create TableModel for results of query SELECT * FROM authors
    tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
    USERNAME, PASSWORD, DEFAULT_QUERY);
    // set up JTextArea in which user types queries
    queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
    queryArea.setWrapStyleWord(true);
    queryArea.setLineWrap(true);
    JScrollPane scrollPane = new JScrollPane(queryArea,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    // set up JButton for submitting queries
    JButton submitButton = new JButton("Submit Query");
    // create Box to manage placement of queryArea and
    // submitButton in GUI
    Box box = Box.createHorizontalBox();
    box.add(scrollPane);
    box.add(submitButton);
    // create JTable delegate for tableModel
    JTable resultTable = new JTable(tableModel);
    resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
    resultTable.setRowSelectionAllowed(true);
    resultTable.getModel().addTableModelListener(this); // step 3
    // place GUI components on content pane
    add(box, BorderLayout.NORTH);
    add(new JScrollPane(resultTable), BorderLayout.CENTER);
    // create event listener for submitButton
    submitButton.addActionListener(
    new ActionListener()
    // pass query to table model
    public void actionPerformed(ActionEvent event)
    // perform a new query
    try
    tableModel.setQuery(queryArea.getText());
    } // end try
    catch ( SQLException sqlException)
    JOptionPane.showMessageDialog(null,
    sqlException.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // try to recover from invalid user query
    // by executing default query
    try {
    tableModel.setQuery(DEFAULT_QUERY);
    queryArea.setText(DEFAULT_QUERY);
    } // end try
    catch (SQLException sqlException2) {
    JOptionPane.showMessageDialog(null,
    sqlException2.getMessage(), "Database error",
    JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end inner catch
    } // end outer catch
    } // end actionPerformed
    } // end ActionListener inner class
    ); // end call to addActionListener
    //...Then set the window size or call pack...
         setSize(750,300);
    setVisible(true); // display window
    } // end try
    catch (ClassNotFoundException classNotFound) {
    JOptionPane.showMessageDialog(null,
    "MySQL driver not found", "Driver not found",
    JOptionPane.ERROR_MESSAGE);
    System.exit(1); // terminate application
    } // end catch
    catch (SQLException sqlException) {
    JOptionPane.showMessageDialog(null, sqlException.getMessage(),
    "Database error", JOptionPane.ERROR_MESSAGE);
    // ensure database connection is closed
    tableModel.disconnectFromDatabase();
    System.exit(1); // terminate application
    } // end catch
    // dispose of window when user quits application (this overrides
    // the default of HIDE_ON_CLOSE)
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    // ensure database connection is closed when user quits application
    addInternalFrameListener(
    new InternalFrameAdapter() {
    // disconnect from database and exit when window has closed
    public void windowClosed(WindowEvent event) {
    tableModel.disconnectFromDatabase();
    System.exit(0);
    } // end method windowClosed
    } // end WindowAdapter inner class
    ); // end call to addWindowListener
    } // end DisplayQueryResults constructor
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    // execute application
    public static void main(String args[]) {
    new DisplayQueryResults();
    } // end main
    } // end class DisplayQueryResults
    My question is in lines 177-187:
    public void tableChanged(TableModelEvent e) { // step 4
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object tableModel = model.getValueAt(row, column);
    // Do something with the data...
    System.out.println(tableModel);
    System.out.println("data");
    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
    If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
    PS:
    When you have solved the problem, please notify me with the code that's changed
    and please share it to others if you like so.
    Best Wishes: Oliver Bob Lagumen
    Email: [email protected]
    website: www.apachevista.com
    Oliver Bob Lagumen
    Edited by: Oliverbob on Jan 24, 2008 9:03 PM

    This is a follow up on the code I have posted above.
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
        }the tableChanged doesnt get called when I would click the cells. The cells are all editable, but as soon as you edit it and press enter, it snaps back to the old data.
    How do we make them editable and how do we notify java that the a cell has changed so that we can send it to the database on that specific column of that specific row?
    Thanks in advance
    Bob

  • Rebuilding JTable

    I'm trying to build a table by first selecting a table name. then i press a button and the table appears. When i change the table name and press the button again the table doesn't change. What is going wrong????
    Here's the code:
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.JInternalFrame;
    public class IPMAC extends JInternalFrame {
         private Connection connection;
    private Statement statement;
         private ResultSet resultSet;
         String selectedGroep;
         private JTable table;
         private int AAP = 1;
    static final int xOffset = 480, yOffset = 10;
         int y, // De y waarde declareren
    x; // De x waarde declareren
    private JComboBox groepKeuze;
    Vector result;
    JDesktopPane desktop;
         public IPMAC()
         throws
                        ClassNotFoundException,
                        SQLException,
                        IllegalAccessException,
                        InstantiationException{
    super("IP MAC",
              false, //resizable
         true, //closable
         false, //maximizable
         true);//iconifiable
              //Set up the GUI.
    desktop = new JDesktopPane(); //a specialized layered pane
    setContentPane(desktop);
    //Set the window's location.
    setLocation(xOffset, yOffset);
    final String url = "jdbc:mysql://localhost/IPMAN";
              final String username = "";
              final String password = "";
              Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         connection = DriverManager.getConnection( url, username, password );
         Label label1 = new Label();
         Label label2 = new Label();
         Label label3 = new Label();
         final TextField macadresveld = new TextField();
         final TextField ipadresveld = new TextField();
         Button button1 = new Button();
         Button button2 = new Button();
         Button button3 = new Button();
              label1.setText("MAC Adres");
              getContentPane().add(label1);
              label1.setBounds(370,60,70,25);
              label2.setText("IP Adres");
              getContentPane().add(label2);
              label2.setBounds(370,110,70,25);
              label3.setText("Groepnaam");
              getContentPane().add(label3);
              label3.setBounds(370,160,70,25);
              getContentPane().add(macadresveld);
              macadresveld.setBounds(440,60,156,20);
              getContentPane().add(ipadresveld);
              ipadresveld.setBounds(440,110,156,20);
              button1.setLabel("Koppel MAC");
              getContentPane().add(button1);
              button1.setBackground(java.awt.Color.lightGray);
              button1.setBounds(506,10,90,25);
              button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
                   JOptionPane.showMessageDialog
                   ( null, "MAC Adres is being added...", "Updating...",     JOptionPane.INFORMATION_MESSAGE);
    try {
              Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
              connection = DriverManager.getConnection( url, username, password );
              Statement stmt = connection.createStatement();
              int numUpdated01 = stmt.executeUpdate("UPDATE ip SET MacAdres = '" + macadresveld.getText() + "' WHERE IpAdres = '" + ipadresveld.getText() + "' ");
              connection.close();
              catch ( ClassNotFoundException cnfex )
              System.err.println(
         "Failed to load JDBC/ODBC driver." );
              cnfex.printStackTrace();
              System.exit( 1 ); // terminate program
              catch ( SQLException sqlex )
              System.err.println( "Unable to connect" );
              sqlex.printStackTrace();
                   JOptionPane.showMessageDialog
                   ( null, "Data has been updated...", "Updated...",     JOptionPane.INFORMATION_MESSAGE);
              button2.setLabel("Save / Exit");
              getContentPane().add(button2);
              button2.setBackground(java.awt.Color.lightGray);
              button2.setBounds(506,300,90,25);
              button2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    setVisible(false);
    dispose();
              button3.setLabel("View Data");
              getContentPane().add(button3);
              button3.setBackground(java.awt.Color.lightGray);
              button3.setBounds(506,265,90,25);
              button3.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                             System.out.println("de gekozen Groep is:" + selectedGroep);
                             try     {
                        getTable();
                             catch(Exception ex)     { }
    groepKeuze = new JComboBox(getContents());
    groepKeuze.setMaximumRowCount(4);
         groepKeuze.setBounds(440,160,156,20);
    groepKeuze.setBackground(java.awt.Color.white);
         getContentPane().add( groepKeuze );
    groepKeuze.addItemListener(new ItemListener() {
         public void itemStateChanged( ItemEvent e ) {
              selectedGroep = groepKeuze.getSelectedItem().toString();
              System.out.println( "de gekozen Groep is:" + selectedGroep );
         setSize(616,370);
              show();
              private Vector getContents()
              throws
              ClassNotFoundException,
              SQLException,
              IllegalAccessException,
              InstantiationException
                   Connection connection;
              Statement statement;
                   ResultSet resultSet;
         final String url = "jdbc:mysql://localhost/IPMAN";
                   final String username = "";
                   final String password = "";
                   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
              connection = DriverManager.getConnection( url, username, password );
                   result = new Vector();
                   String query = "SELECT DISTINCT Groep FROM ip";
              statement = connection.createStatement();
              resultSet = statement.executeQuery( query );
                   while (resultSet.next()) {
                   result.addElement(resultSet.getString("Groep"));
              statement.close();
              return result;
         private void getTable()     throws
              ClassNotFoundException,
              SQLException,
              IllegalAccessException,
              InstantiationException
    Statement statement;
    ResultSet resultSet;
    String query = "SELECT NetwerkAdres,IpAdres,KlasseNetwerk,Groep FROM ip WHERE Groep = '" + selectedGroep + "'";
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
    selectedGroep = "";
    private void displayResultSet( ResultSet rs )
         throws
              ClassNotFoundException,
              SQLException,
              IllegalAccessException,
              InstantiationException {
    boolean moreRecords = rs.next();
    if ( ! moreRecords ) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    table = new JTable( rows, columnHeads );
    JScrollPane scroller = new JScrollPane( table );
    getContentPane().add(scroller);
              scroller.setBounds(0,0,370,325);
    validate();
    private Vector getNextRow( ResultSet rs,
    ResultSetMetaData rsmd )
         throws     ClassNotFoundException,
                   SQLException,
                   IllegalAccessException,
                        InstantiationException{
    Vector currentRow = new Vector();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    switch( rsmd.getColumnType( 1 ) ) {
    case Types.VARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( 1 ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    return currentRow;
    Could somebody try to answer this question???
    thanks!!

    try
    table.getModel().fireTableStructureChanged();
    where you have the validate() line just to see.. I've never actually created a new JTable for every new display, I just manipulate the models and then run the fireTableDataChanged() or fireTableStructureChanged() methods.. That takes care of all this stuff automatically, and I think that'd be a more efficient way of doing things..
    If THAT doens't work, then I'd be suspicious of your scrollpane not redrawing itself.. Do a System.out.println( (String)table.getValueAt(1,1) ); and see if the table actually has the new values or not.. If it DOES but it's not on screen, then you know this is the case.. Then I'd try scroller.revalidate() and scroller.repaint().
    doug

  • JTable question

    I'm implementing the code from Manning's Swing book. The table is rendered correctly but the table model is not saving the edit changes. After a sort or save to a file, I don't see the changes made in the cells. The table is getting refreshed properly though. Can anyone <b> please help</b> ?
    <pre>
    package trunkxref;
    * Copyright 1999-2002 Matthew Robinson and Pavel Vorobiev.
    * All Rights Reserved.
    * ===================================================
    * This program contains code from the book "Swing"
    * 2nd Edition by Matthew Robinson and Pavel Vorobiev
    * http://www.spindoczine.com/sbe
    * ===================================================
    * The above paragraph must be included in full, unmodified
    * and completely intact in the beginning of any source code
    * file that references, copies or uses (in any way, shape
    * or form) code contained in this file.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.net.*;
    public class trnk extends JFrame
    protected JTable m_table;
    protected TrunkReportData m_data;
    public InputStream is;
         Image imginsert, imgdel, imgup, imgdown, imgsav;
    URL jspURL;
    public trnk ( InputStream is, Image imginsert, Image imgdel, Image imgup, Image imgdown, Image imgsav, URL jspURL)
    super ("Trunks Data");
    setSize (600, 300);
         this.is=is;
         this.imginsert=imginsert;
         this.imgdel=imgdel;
         this.imgup=imgup;
         this.imgsav=imgsav;
         this.imgdown=imgdown;
         this.jspURL=jspURL;
    m_data = new TrunkReportData (this,imgup, imgdown);
    m_table = new JTable ();
    m_table.setAutoCreateColumnsFromModel (false);
    m_table.setModel (m_data);
    m_table.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
    for (int k = 0; k < m_data.getColumnCount (); k++)
         TableCellRenderer renderer = null;
         TableCellEditor editor = null;
         renderer = new TextAreaCellRenderer ();     // NEW
         editor = new TextAreaCellEditor ();
         TableColumn column = new TableColumn (k,
              TrunkReportData.m_columns[k].m_width,
                             renderer, editor);
         column.setHeaderRenderer(createDefaultRenderer());
         m_table.addColumn (column);
    JTableHeader header = m_table.getTableHeader ();
    header.setUpdateTableInRealTime (true);
         header.addMouseListener(new ColumnListener());
    header.setReorderingAllowed(true);
    JScrollPane ps = new JScrollPane ();
    ps.getViewport ().setBackground (m_table.getBackground ());
    ps.setSize (550, 150);
    ps.getViewport ().add (m_table);
    getContentPane ().add (ps, BorderLayout.CENTER);
    JToolBar tb = createToolbar ();
    getContentPane ().add (tb, BorderLayout.NORTH);
    JPanel p = new JPanel (new GridLayout (1, 2, 5, 5));
    getContentPane ().add (p, BorderLayout.SOUTH);
    protected TableCellRenderer createDefaultRenderer() {
    DefaultTableCellRenderer label = new DefaultTableCellRenderer()
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    setText((value == null) ? "" : value.toString()) ;
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return this;
    label.setHorizontalAlignment(JLabel.CENTER);
    return label;
    protected JToolBar createToolbar ()
    JToolBar tb = new JToolBar ();
    tb.setFloatable (false);
    JButton bt = new JButton (new ImageIcon (imginsert));
    //JButton bt = new JButton ("Insert");
    bt.setToolTipText ("Insert Row");
    bt.setRequestFocusEnabled (false);
    ActionListener lst = new ActionListener (){
    public void actionPerformed (ActionEvent e) {
         int nRow = m_table.getSelectedRow() + 1;
         m_data.insert (nRow);
         m_table.tableChanged (new TableModelEvent
         (m_data, nRow, nRow, TableModelEvent.ALL_COLUMNS,
         TableModelEvent.INSERT));
         m_table.setRowSelectionInterval (nRow, nRow);
    bt.addActionListener ((ActionListener)lst);
    tb.add (bt);
    bt = new JButton (new ImageIcon (imgdel));
    //bt = new JButton ("Delete");
    bt.setToolTipText("Delete Row");
    bt.setRequestFocusEnabled(false);
    lst = new ActionListener ()
         public void
         actionPerformed
         (ActionEvent e)
         int nRow = m_table.getSelectedRow();
         if (m_data.delete (nRow))
              m_table.tableChanged
              (new TableModelEvent
              (m_data, nRow, nRow,
              TableModelEvent.ALL_COLUMNS,
              TableModelEvent.DELETE));
              m_table.clearSelection();
         bt.addActionListener(lst);
         tb.add (bt);
    bt = new JButton (new ImageIcon (imgsav));
    //bt = new JButton ("Save");
    bt.setToolTipText("Save");
    bt.setRequestFocusEnabled(false);
    lst = new ActionListener ()
         public void
         actionPerformed
         (ActionEvent e)
         m_table.tableChanged (new TableModelEvent
         (m_data));
              //m_data.fireTableDataChanged();
              System.out.println("beginning to write data to" + jspURL.toString());
              //code to save data to file
              String txt="";
              Enumeration enum=m_data.m_vector.elements();
              while(enum.hasMoreElements())
                   TrunkData trnk = (TrunkData)enum.nextElement();
                   txt += trnk.m_sysname + " , "
                        + trnk.m_clli + " , "
                        + trnk.m_tg + " , "
                        + trnk.m_member.intValue() + " , "
                        + trnk.m_trunk_type + " , "
                        + trnk.m_lata + " , "
                        + trnk.m_lata_name + " , "
                        + trnk.m_prospect_server + " , "
                        + trnk.m_tgroupid + " , "
                        + trnk.m_ctg + " , "
                        + trnk.m_augmen.intValue() + " , "
                        + trnk.m_vendor + "\n";
              try {
              URLConnection jspCon=jspURL.openConnection();
              jspCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
              jspCon.setUseCaches(false);
              jspCon.setDoOutput(true);
              PrintStream out = new PrintStream(jspCon.getOutputStream());
              String postData= "Text=" + URLEncoder.encode(txt, "UTF-8");
              out.println(postData);
              out.flush();
              out.close();
              InputStreamReader in=new InputStreamReader(jspCon.getInputStream());
              int chr;
              while((chr=in.read()) != -1) {}
              in.close();
              } catch (Exception e2) {
                   System.out.println (" exception in writing data out "
                   + e2.toString());
              System.out.println("done write data");
         bt.addActionListener(lst);
         tb.add (bt);
         return tb;
         // NEW
         class ColumnListener extends MouseAdapter {
              public void mouseClicked(MouseEvent e) {
         m_table.tableChanged (new TableModelEvent
         (m_data));
                   //m_data.fireTableDataChanged();
                   TableColumnModel colModel = m_table.getColumnModel();
                   int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
                   int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();
                   if (modelIndex < 0)
                        return;
                   if (m_data.m_sortCol == modelIndex)
                        m_data.m_sortAsc = !m_data.m_sortAsc;
                   else
                        m_data.m_sortCol = modelIndex;
                   for (int i=0; i < m_data.getColumnCount(); i++) {
                        TableColumn column = colModel.getColumn(i);
                        int index = column.getModelIndex();
                        JLabel renderer = (JLabel)column.getHeaderRenderer();
                        renderer.setIcon(m_data.getColumnIcon(index));
                   m_table.getTableHeader().repaint();
                   m_data.sortData();
                   m_table.tableChanged(new TableModelEvent(m_data));
                   m_table.repaint();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
    protected static Border m_noFocusBorder = new
    EmptyBorder (1,          1,          1,          1);
    protected static Border m_focusBorder =
    UIManager.getBorder("Table.focusCellHighlightBorder");
    public
    TextAreaCellRenderer
    setEditable
         (false);
    setLineWrap
         (true);
    setWrapStyleWord
         (true);
    setBorder
         (m_noFocusBorder);}
    public Component
    getTableCellRendererComponent
    (JTable table,
    Object value,
    boolean
    isSelected,
    boolean
    hasFocus,
    int nRow, int nCol)
    if (value     instanceof     String)
         setText ((String) value);
         else if (value instanceof Integer)
         setText((String)value.toString());
    setBackground
         (isSelected && !hasFocus ?     table.getSelectionBackground() : table.getBackground ());
    setForeground
         (isSelected
         && !hasFocus ?
         table.getSelectionForeground() : table.getForeground ());
    setFont (table.getFont ());
    setBorder (hasFocus ? m_focusBorder : m_noFocusBorder);
    // Adjust row's
    // height
    int width =
         table.getColumnModel().getColumn(nCol).getWidth ();
    setSize (width,
         1000);
    int rowHeight =     getPreferredSize().height;
    if (table.getRowHeight(nRow) != rowHeight)
         table.setRowHeight (nRow, rowHeight);
    return this;}
    // To fix JDK bug
    public String getToolTipText (MouseEvent event)
    return null;
    // NEW
    class TextAreaCellEditor extends AbstractCellEditor implements
    TableCellEditor
    public static int CLICK_COUNT_TO_EDIT = 1;
    protected JTextArea m_textArea;
    protected JScrollPane m_scroll;
    public TextAreaCellEditor ()
         m_textArea = new JTextArea ();
         m_textArea.setLineWrap (true);
         m_textArea.setWrapStyleWord (true);
         m_scroll = new JScrollPane (m_textArea,
         //JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
         JScrollPane.VERTICAL_SCROLLBAR_NEVER,
         //JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    public Component
    getTableCellEditorComponent
    (JTable table,
    Object value,
    boolean
    isSelected,
    int nRow, int nCol)
         m_textArea.setBackground(table.getBackground());
         m_textArea.setForeground(table.getForeground());
         m_textArea.setFont (table.getFont());
         m_textArea.setText (value == null ? "" : value.toString());
         return m_scroll;
    public Object getCellEditorValue ()
         return     m_textArea.getText ();
    public boolean isCellEditable (EventObject anEvent)
         if (anEvent instanceof     MouseEvent)
         int click = ((MouseEvent) anEvent).getClickCount();
         return click >= CLICK_COUNT_TO_EDIT;
         return true;
    class TrunkData
    public String m_sysname;
    public String m_clli;
    public String m_tg;
    public Integer m_member;
    public String m_trunk_type;
    public String m_lata;
    public String m_lata_name;
    public String m_prospect_server;
    public String m_tgroupid;
    public String m_ctg;
    public Integer m_augmen;
    public String m_vendor;
    public TrunkData ()
    m_sysname = "";
    m_clli = "";
    m_tg = "";
    m_member =     new Integer (0);
    m_trunk_type =     "";
    m_lata = "";
    m_lata_name =     "";
    m_prospect_server     = "";
    m_tgroupid = "";
    m_ctg = "";
    m_augmen = new Integer(0);
    m_vendor = "";
    public
    TrunkData
    (String sys,
    String clli,
    String tg,
    String member,
    String ttyp,
    String lata,
    String latanm,
    String pserver,
    String tgrpid,
    String ctg,
    String aug,
    String vend)
    m_sysname = sys;
    m_clli = clli;
    m_tg = tg;
         try {
         if (member.trim().equals(""))
         m_member=new Integer(0);
         else
    m_member =     new Integer(member.trim());
         } catch (Exception e) {
              System.out.println("can't parse member " + e.toString());
    m_trunk_type =     ttyp;
    m_lata = lata;
    m_lata_name =     latanm;
    m_prospect_server     = pserver;
    m_tgroupid =     tgrpid;
    m_ctg = ctg;
         if (aug.trim().equals(""))
         m_augmen=new Integer(0);
         else m_augmen=new Integer(aug.trim());
    m_vendor = vend;
    class ColumnData
    public String m_tolatLbl;
    int m_width;
    int m_alignment;
    public ColumnData (String title, int width, int alignment)
    m_tolatLbl =     title;
    m_width = width;
    m_alignment =     alignment;
    class TrunkReportData extends AbstractTableModel
    public static ImageIcon COLUMN_UP;
    public static ImageIcon COLUMN_DOWN;
    public int m_sortCol = 0;
    public boolean m_sortAsc = true;
    public static final ColumnData m_columns[] =
    new ColumnData ("System", 200, JLabel.LEFT),
    new ColumnData ("CLLI", 200, JLabel.LEFT),
    new ColumnData ("Trunk Group", 200, JLabel.LEFT),
    new ColumnData ("Members", 200, JLabel.LEFT),
    new ColumnData ("Trunk Type", 200, JLabel.LEFT),
    new ColumnData ("LATA ", 200, JLabel.LEFT),
    new ColumnData ("LATA Name", 200, JLabel.LEFT),
    new ColumnData ("Prospect Server", 200, JLabel.LEFT),
    new ColumnData ("Trunk Group ID", 200, JLabel.LEFT),
    new ColumnData ("CTG", 200, JLabel.LEFT),
    new ColumnData ("Augments", 200, JLabel.LEFT),
    new ColumnData ("Vendor", 200, JLabel.LEFT)
    protected trnk m_parent;
    protected Vector m_vector;
    public TrunkReportData (trnk parent , Image imgup, Image imgdown)
         this.COLUMN_UP=new ImageIcon(imgup);
         this.COLUMN_DOWN=new ImageIcon(imgdown);
    m_parent = parent;
    m_vector = new Vector ();
    setDefaultData (parent.is);
    public void setDefaultData (InputStream is)
    m_vector = new Vector ();
    int numFields =     0;
    try
    BufferedReader
         br =new     BufferedReader(new InputStreamReader(is));
    String inline ="";
    while ((inline = br.readLine()) != null)
         if (inline.indexOf('#') > -1)
         continue;
         StringTokenizer st = new StringTokenizer (inline, ",");
         String nsys=st.nextToken ().trim(); //sys
         String nclli= st.nextToken().trim() ;     // clli
         String ntg= st.nextToken ().trim();     // tg
         String nmemb= st.nextToken().trim();     // members
         String nttyp= st.nextToken ().trim();     // trunktype
         String nlata= st.nextToken ().trim();     // lata
         String nlataname= st.nextToken ().trim();     // lata name
         String npros= st.nextToken ().trim();     // prospect server
         String ntgrpid=st.nextToken().trim();      //tgroupid
         String nctg=st.nextToken().trim();      //ctg
         String naug=st.nextToken().trim();      //augments
         String nvend=st.nextToken().trim();      //vendor
         m_vector.addElement(new TrunkData(nsys,nclli, ntg,
              nmemb, nttyp, nlata, nlataname, npros, ntgrpid, nctg,
              naug,nvend));
    br.close ();}
    catch (Exception e)
    System.out.println("Error in file reader 2 "+ e.toString ());
         sortData();
    public Icon getColumnIcon(int column) { // NEW
    if (column==m_sortCol)
    return m_sortAsc ? COLUMN_UP : COLUMN_DOWN;
    return null;
    // NEW
    public void sortData() {
    Collections.sort(m_vector, new
    TrunkComparator(m_sortCol, m_sortAsc));
    public int getRowCount ()
    return m_vector == null ? 0 : m_vector.size ();
    public int getColumnCount ()
    return m_columns.length;
    public String getColumnName(int nCol)
    return m_columns[nCol]. m_tolatLbl;
    public boolean isCellEditable
    (int nRow, int nCol)
    return true;
    public Object getValueAt (int     nRow,     int nCol)
    if (nRow < 0 || nRow >=getRowCount())
    return "";
    TrunkData row = (TrunkData) m_vector.elementAt(nRow);
    switch (nCol)
    case 0:
    return row.m_sysname;
    case 1:
    return row.m_clli;
    case 2:
    return row.m_tg;
    case 3:
    return row.m_member;
    case 4:
    return row.m_trunk_type;
    case 5:
    return row.m_lata;
    case 6:
    return row.m_lata_name;
    case 7:
    return row.m_prospect_server;
    case 8:
    return row.m_tgroupid;
    case 9:
    return row.m_ctg;
    case 10:
    return row.m_augmen;
    case 11:
    return row.m_vendor;
    return "";
    public void setValueAt (Object value, int nRow, int nCol)
    if (nRow < 0
    || nRow >=
    getRowCount
    || value ==
    null)
    return;
    System.out.println("setting nrow=" + nRow + " nCol=" + nCol + " to value=" + (String) value);
    TrunkData row = (TrunkData) m_vector.elementAt (nRow);
    String svalue = value.toString ();
    switch (nCol)
    case 0:
    row.m_sysname = svalue; break;
    case 1:
    row.m_clli = svalue; break;
    case 2:
    row.m_tg = svalue; break;
    case 3:
         if (svalue.trim().equals(""))
         row.m_member=new Integer(0);
         else
    row.m_member = new Integer(svalue.trim()); break;
    case 4:
    row.m_trunk_type = svalue; break;
    case 5:
    row.m_lata = svalue; break;
    case 6:
    row.m_lata_name = svalue; break;
    case 7:
    row.m_prospect_server = svalue; break;
    case 8:
    row.m_tgroupid = svalue; break;
    case 9:
    row.m_ctg = svalue; break;
    case 10:
    row.m_augmen = new Integer(svalue.trim()); break;
    case 11:
    row.m_vendor = svalue; break;}
         fireTableCellUpdated(nRow,nCol);
    public void insert (int nRow)
    if (nRow < 0)
    nRow = 0;
    if (nRow >     m_vector.size ())
    nRow =
    m_vector. size ();
    m_vector.insertElementAt
    (new
    TrunkData (),
    nRow);
    public boolean delete (int nRow)
    if (nRow < 0
    || nRow >=
    m_vector.size
    ())return
         false;
    m_vector.remove (nRow);
    return true;
    class TrunkComparator implements Comparator {
         protected int m_sortCol;
    protected boolean m_sortAsc;
    public TrunkComparator(int sortCol, boolean sortAsc) {
    m_sortCol = sortCol;
    m_sortAsc = sortAsc;
         public int compare(Object o1, Object o2)
              if (!(o1 instanceof TrunkData) || !(o2 instanceof TrunkData))
              return 0;
              TrunkData s1=(TrunkData)o1;
              TrunkData s2=(TrunkData)o2;
              int result=0;
              String str1="", str2="";
              int i1=0, i2=0;
              switch(m_sortCol) {
                   case 0: //sysname
                   str1=(String)s1.m_sysname;
                   str2=(String)s2.m_sysname;
                   result=str1.compareTo(str2);
                   break;
                   case 1: // clli
                   str1=(String)s1.m_clli;
                   str2=(String)s2.m_clli;
                   result=str1.compareTo(str2);
                   break;
                   case 2: //TG
                   str1=(String)s1.m_tg;
                   str2=(String)s2.m_tg;
                   result=str1.compareTo(str2);
                   break;
                   case 3: //member
                   i1 =s1.m_member.intValue();
                   i2 =s2.m_member.intValue();
                   result = i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
                   break;
                   case 4: //trunk type
                   str1=(String)s1.m_trunk_type;
                   str2=(String)s2.m_trunk_type;
                   result=str1.compareTo(str2);
                   break;
                   case 5: //lata
                   str1=(String)s1.m_lata;
                   str2=(String)s2.m_lata;
                   result=str1.compareTo(str2);
                   break;
                   case 6: //lata name
                   str1=(String)s1.m_lata_name;
                   str2=(String)s2.m_lata_name;
                   result=str1.compareTo(str2);
                   break;
                   case 7: //prospect server
                   str1=(String)s1.m_prospect_server;
                   str2=(String)s2.m_prospect_server;
                   result=str1.compareTo(str2);
                   break;
                   case 8: //tgroup id
                   str1=(String)s1.m_tgroupid;
                   str2=(String)s2.m_tgroupid;
                   result=str1.compareTo(str2);
                   break;
                   case 9: //ctg
                   str1=(String)s1.m_ctg;
                   str2=(String)s2.m_ctg;
                   result=str1.compareTo(str2);
                   break;
                   case 10: //augments
                   i1 =s1.m_augmen.intValue();
                   i2 =s2.m_augmen.intValue();
                   result = i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
                   break;
                   case 11: //vendor
                   str1=(String)s1.m_vendor;
                   str2=(String)s2.m_vendor;
                   result=str1.compareTo(str2);
                   break;
         if (!m_sortAsc) result = -result;
         return result;
         public boolean equals(Object obj) {
              if (obj instanceof TrunkComparator) {
                   TrunkComparator compObj=(TrunkComparator) obj;
                   return (compObj.m_sortCol == m_sortCol) &&
                        (compObj.m_sortAsc==m_sortAsc);
              return false;
    </pre>

    Sorry about the code mess. I'm trying to use the JFrame inside an applet. Is there some way to make the applet show up inside the browser instead of as a separate window as it is doing now? I've searched through the posts in this forum without much result. I gleaned this from jguru.com but don't know how to implement:
    If you would like to have Frames appear in the web page itself, you could add a JDesktopPane to a JApplet, and add JInternalFrames to it. This of course requires Swing, and the best way to ensure this is to use the Java Plug-in from Sun (http://java.sun.com/products/plugin/).
    I want to use Tab key to move between cells. I've researched that matter in this forum but don't have a good solution yet. Please help .
    package trunkxref;
    *  Copyright 1999-2002 Matthew Robinson and Pavel Vorobiev.
    *  All Rights Reserved.
    *  ===================================================
    *  This program contains code from the book "Swing"
    *  2nd Edition by Matthew Robinson and Pavel Vorobiev
    *  http://www.spindoczine.com/sbe
    *  ===================================================
    *  The above paragraph must be included in full, unmodified
    *  and completely intact in the beginning of any source code
    *  file that references, copies or uses (in any way, shape
    *  or form) code contained in this file.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.net.*;
    public class trnk extends JFrame
      protected JTable m_table;
      protected TrunkReportData m_data;
      public InputStream is;
         Image imginsert, imgdel, imgup, imgdown, imgsav;
      URL jspURL;
      public trnk ( InputStream is, Image imginsert, Image imgdel, Image imgup, Image imgdown, Image imgsav, URL jspURL)
        super ("Trunks Data");
        setSize (600, 300);
         this.is=is;
         this.imginsert=imginsert;
         this.imgdel=imgdel;
         this.imgup=imgup;
         this.imgsav=imgsav;
         this.imgdown=imgdown;
         this.jspURL=jspURL;
        m_data = new TrunkReportData (this,imgup, imgdown);
        m_table = new JTable ();
        m_table.setAutoCreateColumnsFromModel (false);
        m_table.setModel (m_data);
        m_table.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
        for (int k = 0; k < m_data.getColumnCount (); k++)
         TableCellRenderer renderer = null;
         TableCellEditor editor = null;
         renderer = new TextAreaCellRenderer ();     // NEW
         editor = new TextAreaCellEditor ();
         TableColumn column = new TableColumn (k,
              TrunkReportData.m_columns[k].m_width,
                                   renderer, editor);
         column.setHeaderRenderer(createDefaultRenderer());
         m_table.addColumn (column);
        JTableHeader header = m_table.getTableHeader ();
        header.setUpdateTableInRealTime (true);
         header.addMouseListener(new ColumnListener());
            header.setReorderingAllowed(true);
        JScrollPane ps = new JScrollPane ();
        ps.getViewport ().setBackground (m_table.getBackground ());
        ps.setSize (550, 150);
        ps.getViewport ().add (m_table);
        getContentPane ().add (ps, BorderLayout.CENTER);
        JToolBar tb = createToolbar ();
        getContentPane ().add (tb, BorderLayout.NORTH);
        JPanel p = new JPanel (new GridLayout (1, 2, 5, 5));
        getContentPane ().add (p, BorderLayout.SOUTH);
    protected TableCellRenderer createDefaultRenderer() {
          DefaultTableCellRenderer label = new DefaultTableCellRenderer()
                    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                                   if (table != null) {
                                     JTableHeader header = table.getTableHeader();
                                            if (header != null) {
                                                setForeground(header.getForeground());
                                                setBackground(header.getBackground());
                                                    setFont(header.getFont());
                                    setText((value == null) ? "" : value.toString()) ;
                                  setBorder(UIManager.getBorder("TableHeader.cellBorder"));
                                    return this;
                    label.setHorizontalAlignment(JLabel.CENTER);
                    return label;
      protected JToolBar createToolbar ()
        JToolBar tb = new JToolBar ();
        tb.setFloatable (false);
        JButton bt = new JButton (new ImageIcon (imginsert));
        //JButton bt = new JButton ("Insert");
        bt.setToolTipText ("Insert Row");
        bt.setRequestFocusEnabled (false);
        ActionListener lst = new ActionListener (){
           public void actionPerformed (ActionEvent e) {
         int nRow = m_table.getSelectedRow() + 1;
         m_data.insert (nRow);
         m_table.tableChanged (new TableModelEvent
            (m_data, nRow, nRow, TableModelEvent.ALL_COLUMNS,
             TableModelEvent.INSERT));
         m_table.setRowSelectionInterval (nRow, nRow);
        bt.addActionListener ((ActionListener)lst);
        tb.add (bt);
        bt = new JButton (new ImageIcon (imgdel));
        //bt = new JButton ("Delete");
        bt.setToolTipText("Delete Row");
        bt.setRequestFocusEnabled(false);
        lst = new ActionListener ()
         public void
           actionPerformed
           (ActionEvent e)
             int nRow = m_table.getSelectedRow();
             if (m_data.delete (nRow))
              m_table.tableChanged
                (new TableModelEvent
                 (m_data, nRow, nRow,
                  TableModelEvent.ALL_COLUMNS,
                  TableModelEvent.DELETE));
              m_table.clearSelection();
         bt.addActionListener(lst);
         tb.add (bt);
        bt = new JButton (new ImageIcon (imgsav));
        //bt = new JButton ("Save");
        bt.setToolTipText("Save");
        bt.setRequestFocusEnabled(false);
        lst = new ActionListener ()
         public void
           actionPerformed
           (ActionEvent e)
         m_table.tableChanged (new TableModelEvent
            (m_data));
              //m_data.fireTableDataChanged();
              System.out.println("beginning to write data to" + jspURL.toString());
              //code to save data to file
              String txt="";
              Enumeration enum=m_data.m_vector.elements();
              while(enum.hasMoreElements())
                   TrunkData trnk = (TrunkData)enum.nextElement();
                   txt += trnk.m_sysname + " , "
                        + trnk.m_clli + " , "
                        + trnk.m_tg + " , "
                        + trnk.m_member.intValue() + " , "
                        + trnk.m_trunk_type + " , "
                        + trnk.m_lata + " , "
                        + trnk.m_lata_name + " , "
                        + trnk.m_prospect_server + " , "
                        + trnk.m_tgroupid + " , "
                        + trnk.m_ctg + " , "
                        + trnk.m_augmen.intValue() + " , "
                        + trnk.m_vendor + "\n";
              try {
              URLConnection jspCon=jspURL.openConnection();
              jspCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
              jspCon.setUseCaches(false);
              jspCon.setDoOutput(true);
              PrintStream out = new PrintStream(jspCon.getOutputStream());
              String postData= "Text=" + URLEncoder.encode(txt, "UTF-8");
              out.println(postData);
              out.flush();
              out.close();
              InputStreamReader in=new InputStreamReader(jspCon.getInputStream());
              int chr;
              while((chr=in.read()) != -1) {}
              in.close();
              } catch (Exception e2) {
                   System.out.println (" exception in writing data out "
                   + e2.toString());
              System.out.println("done write data");
         bt.addActionListener(lst);
         tb.add (bt);
         return tb;
         // NEW
         class ColumnListener extends MouseAdapter {
              public void mouseClicked(MouseEvent e) {
         m_table.tableChanged (new TableModelEvent
            (m_data));
                   //m_data.fireTableDataChanged();
                   TableColumnModel colModel = m_table.getColumnModel();
                   int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
                   int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();
                   if (modelIndex < 0)
                        return;
                   if (m_data.m_sortCol == modelIndex)
                        m_data.m_sortAsc = !m_data.m_sortAsc;
                   else
                        m_data.m_sortCol = modelIndex;
                   for (int i=0; i < m_data.getColumnCount(); i++) {
                        TableColumn column = colModel.getColumn(i);
                        int index = column.getModelIndex();
                        JLabel renderer = (JLabel)column.getHeaderRenderer();
                        renderer.setIcon(m_data.getColumnIcon(index));
                   m_table.getTableHeader().repaint();
                   m_data.sortData();
                   m_table.tableChanged(new TableModelEvent(m_data));
                   m_table.repaint();
      class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
        protected static Border m_noFocusBorder    =    new
        EmptyBorder (1,           1,           1,           1);
        protected static    Border    m_focusBorder =
        UIManager.getBorder("Table.focusCellHighlightBorder");
        public
        TextAreaCellRenderer
          setEditable
         (false);
          setLineWrap
         (true);
          setWrapStyleWord
         (true);
          setBorder
         (m_noFocusBorder);}
        public Component
        getTableCellRendererComponent
        (JTable table,
         Object value,
         boolean
         isSelected,
         boolean
         hasFocus,
         int nRow, int nCol)
          if (value       instanceof       String)
         setText ((String) value);
         else if (value instanceof Integer)
         setText((String)value.toString());
          setBackground
         (isSelected && !hasFocus ?      table.getSelectionBackground() : table.getBackground ());
          setForeground
         (isSelected
          && !hasFocus ?
          table.getSelectionForeground() : table.getForeground ());
          setFont (table.getFont ());
          setBorder (hasFocus ? m_focusBorder : m_noFocusBorder);
          // Adjust row's
          // height
          int width =
         table.getColumnModel().getColumn(nCol).getWidth ();
          setSize (width,
                1000);
          int rowHeight =     getPreferredSize().height;
          if (table.getRowHeight(nRow) !=  rowHeight)
         table.setRowHeight (nRow,  rowHeight);
          return this;}
        // To fix JDK bug
        public String getToolTipText (MouseEvent event)
          return null;
      // NEW
      class TextAreaCellEditor extends AbstractCellEditor implements
      TableCellEditor
    public static int CLICK_COUNT_TO_EDIT = 1;
          protected JTextArea m_textArea;
        protected JScrollPane m_scroll;
        public TextAreaCellEditor ()
         m_textArea = new JTextArea ();
         m_textArea.setLineWrap (true);
         m_textArea.setWrapStyleWord (true);
         m_scroll = new JScrollPane (m_textArea,
            //JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.VERTICAL_SCROLLBAR_NEVER,
            //JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public Component
          getTableCellEditorComponent
          (JTable table,
           Object value,
           boolean
           isSelected,
           int nRow, int nCol)
         m_textArea.setBackground(table.getBackground());
         m_textArea.setForeground(table.getForeground());
         m_textArea.setFont (table.getFont());
         m_textArea.setText (value   ==   null ?   "" :  value.toString());
         return m_scroll;
        public Object getCellEditorValue ()
         return       m_textArea.getText ();
        public boolean isCellEditable (EventObject anEvent)
         if (anEvent   instanceof         MouseEvent)
             int click = ((MouseEvent) anEvent).getClickCount();
             return click >= CLICK_COUNT_TO_EDIT;
         return true;
      class TrunkData
        public String    m_sysname;
        public String    m_clli;
        public String    m_tg;
        public Integer     m_member;
        public String    m_trunk_type;
        public String    m_lata;
        public String    m_lata_name;
        public String    m_prospect_server;
        public String    m_tgroupid;
        public String    m_ctg;
        public Integer   m_augmen;
        public String    m_vendor;
        public TrunkData ()
          m_sysname = "";
          m_clli = "";
          m_tg = "";
          m_member =     new Integer (0);
          m_trunk_type =     "";
          m_lata = "";
          m_lata_name =       "";
          m_prospect_server       = "";
          m_tgroupid = "";
          m_ctg = "";
          m_augmen = new Integer(0);
          m_vendor = "";
        public
        TrunkData
        (String sys,
         String clli,
         String tg,
         String member,
         String ttyp,
         String lata,
         String latanm,
         String pserver,
         String tgrpid,
         String ctg,
         String aug,
         String vend)
          m_sysname = sys;
          m_clli = clli;
          m_tg = tg;
         try {
         if (member.trim().equals(""))
         m_member=new Integer(0);
         else
          m_member =     new Integer(member.trim());
         } catch (Exception e) {
              System.out.println("can't parse member " + e.toString());
          m_trunk_type =     ttyp;
          m_lata = lata;
          m_lata_name =     latanm;
          m_prospect_server     = pserver;
          m_tgroupid =     tgrpid;
          m_ctg = ctg;
         if (aug.trim().equals(""))
         m_augmen=new Integer(0);
         else m_augmen=new Integer(aug.trim());
          m_vendor = vend;
      class ColumnData
        public String    m_tolatLbl;
        int m_width;
        int m_alignment;
        public    ColumnData    (String title,     int width,     int alignment)
          m_tolatLbl =     title;
          m_width = width;
          m_alignment =     alignment;
      class  TrunkReportData  extends  AbstractTableModel
    public static ImageIcon COLUMN_UP;
            public static ImageIcon COLUMN_DOWN;
        public int               m_sortCol = 0;
            public boolean m_sortAsc = true;
        public static      final ColumnData      m_columns[] =
          new      ColumnData      ("System", 200,       JLabel.LEFT),
          new      ColumnData      ("CLLI", 200,       JLabel.LEFT),
          new      ColumnData      ("Trunk Group",       200,       JLabel.LEFT),
          new      ColumnData      ("Members", 200,       JLabel.LEFT),
          new      ColumnData      ("Trunk Type",       200,       JLabel.LEFT),
          new      ColumnData      ("LATA ", 200,       JLabel.LEFT),
          new      ColumnData      ("LATA Name",       200,       JLabel.LEFT),
          new      ColumnData      ("Prospect Server",       200,       JLabel.LEFT),
          new      ColumnData      ("Trunk Group ID",       200,       JLabel.LEFT),
          new      ColumnData      ("CTG", 200,       JLabel.LEFT),
          new      ColumnData      ("Augments", 200,       JLabel.LEFT),
          new      ColumnData      ("Vendor", 200,       JLabel.LEFT)
        protected      trnk m_parent;
        protected Vector      m_vector;
        public TrunkReportData (trnk parent , Image imgup, Image imgdown)
         this.COLUMN_UP=new ImageIcon(imgup);
         this.COLUMN_DOWN=new ImageIcon(imgdown);
          m_parent = parent;
          m_vector = new Vector ();
          setDefaultData (parent.is);
        public void setDefaultData (InputStream is)
          m_vector =  new Vector ();
        int numFields =       0;
        try
          BufferedReader
         br =new     BufferedReader(new InputStreamReader(is));
          String inline ="";
          while ((inline =  br.readLine()) != null)
           if (inline.indexOf('#') > -1)
               continue;
           StringTokenizer st = new StringTokenizer (inline, ",");
           String nsys=st.nextToken ().trim(); //sys
           String nclli=  st.nextToken().trim() ;     // clli
           String ntg= st.nextToken ().trim();     // tg
           String nmemb=  st.nextToken().trim();     // members
           String nttyp=   st.nextToken ().trim();     // trunktype
           String nlata= st.nextToken ().trim();     // lata
           String nlataname=  st.nextToken ().trim();     // lata  name
           String npros=    st.nextToken ().trim();     // prospect  server
           String ntgrpid=st.nextToken().trim();      //tgroupid
           String nctg=st.nextToken().trim();      //ctg
           String naug=st.nextToken().trim();      //augments
           String nvend=st.nextToken().trim();      //vendor
            m_vector.addElement(new TrunkData(nsys,nclli, ntg,
              nmemb, nttyp, nlata, nlataname, npros, ntgrpid, nctg,
              naug,nvend));
          br.close ();}
        catch (Exception e)
          System.out.println("Error in file reader 2 "+ e.toString ());
         sortData();
    public Icon getColumnIcon(int column) { // NEW
                    if (column==m_sortCol)
                            return m_sortAsc ? COLUMN_UP : COLUMN_DOWN;
                    return null;
    // NEW
            public void sortData() {
                    Collections.sort(m_vector, new
                            TrunkComparator(m_sortCol, m_sortAsc));
    public int getRowCount ()
      return m_vector == null ? 0 : m_vector.size ();
    public int getColumnCount ()
      return    m_columns.length;
    public String getColumnName(int nCol)
      return    m_columns[nCol]. m_tolatLbl;
    public boolean isCellEditable
    (int nRow, int nCol)
      return true;
    public Object getValueAt (int         nRow,         int nCol)
      if (nRow < 0 || nRow >=getRowCount())
        return "";
      TrunkData row = (TrunkData) m_vector.elementAt(nRow);
      switch (nCol)
        case 0:
          return row.m_sysname;
        case 1:
          return row.m_clli;
        case 2:
          return row.m_tg;
        case 3:
          return row.m_member;
        case 4:
          return row.m_trunk_type;
        case 5:
          return row.m_lata;
        case 6:
          return row.m_lata_name;
        case 7:
          return row.m_prospect_server;
        case 8:
          return row.m_tgroupid;
        case 9:
          return row.m_ctg;
        case 10:
          return row.m_augmen;
        case 11:
          return row.m_vendor;
      return "";
    public void setValueAt (Object value, int nRow, int nCol)
      if (nRow < 0
          || nRow >=
          getRowCount
          || value ==
          null)
        return;
    System.out.println("setting nrow=" + nRow + " nCol=" + nCol + " to value=" + (String) value);
      TrunkData row = (TrunkData) m_vector.elementAt (nRow);
      String svalue = value.toString ();
      switch (nCol)
        case 0:
          row.m_sysname = svalue; break;
        case 1:
          row.m_clli = svalue; break;
        case 2:
          row.m_tg = svalue; break;
        case 3:
         if (svalue.trim().equals(""))
         row.m_member=new Integer(0);
         else
          row.m_member = new Integer(svalue.trim()); break;
        case 4:
          row.m_trunk_type = svalue; break;
        case 5:
          row.m_lata = svalue; break;
        case 6:
          row.m_lata_name = svalue; break;
        case 7:
          row.m_prospect_server = svalue; break;
        case 8:
          row.m_tgroupid = svalue; break;
        case 9:
          row.m_ctg = svalue; break;
        case 10:
          row.m_augmen = new Integer(svalue.trim()); break;
        case 11:
          row.m_vendor = svalue; break;}
         fireTableCellUpdated(nRow,nCol);
    public void insert (int nRow)
      if (nRow < 0)
        nRow = 0;
      if (nRow >     m_vector.size ())
        nRow  =
          m_vector. size ();
      m_vector.insertElementAt
        (new
         TrunkData (),
         nRow);
    public boolean delete (int nRow)
      if (nRow < 0
          || nRow >=
          m_vector.size
          ())return
            false;
      m_vector.remove (nRow);
      return true;
    class TrunkComparator implements Comparator {
          protected int            m_sortCol;
            protected boolean m_sortAsc;
            public TrunkComparator(int sortCol, boolean sortAsc) {
                    m_sortCol = sortCol;
                    m_sortAsc = sortAsc;
         public int compare(Object o1, Object o2)
              if (!(o1 instanceof TrunkData) || !(o2 instanceof TrunkData))
              return 0;
              TrunkData s1=(TrunkData)o1;
              TrunkData s2=(TrunkData)o2;
              int result=0;
              String str1="", str2="";
              int i1=0, i2=0;
              switch(m_sortCol) {
                   case 0: //sysname
                   str1=(String)s1.m_sysname;
                   str2=(String)s2.m_sysname;
                   result=str1.compareTo(str2);
                   break;
                   case 1: // clli
                   str1=(String)s1.m_clli;
                   str2=(String)s2.m_clli;
                   result=str1.compareTo(str2);
                   break;
                   case 2: //TG
                   str1=(String)s1.m_tg;
                   str2=(String)s2.m_tg;
                   result=str1.compareTo(str2);
                   break;
                   case 3: //member
                   i1 =s1.m_member.intValue();
                   i2 =s2.m_member.intValue();
                   result = i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
                   break;
                   case 4: //trunk type
                   str1=(String)s1.m_trunk_type;
                   str2=(String)s2.m_trunk_type;
                   result=str1.compareTo(str2);
                   break;
                   case 5: //lata
                   str1=(String)s1.m_lata;
                   str2=(String)s2.m_lata;
                   result=str1.compareTo(str2);
                   break;
                   case 6: //lata name
                   str1=(String)s1.m_lata_name;
                   str2=(String)s2.m_lata_name;
                   result=str1.compareTo(str2);
                   break;
                   case 7: //prospect server
                   str1=(String)s1.m_prospect_server;
                   str2=(String)s2.m_prospect_server;
                   result=str1.compareTo(str2);
                   break;
                   case 8: //tgroup id
                   str1=(String)s1.m_tgroupid;
                   str2=(String)s2.m_tgroupid;
                   result=str1.compareTo(str2);
                   break;
                   case 9: //ctg
                   str1=(String)s1.m_ctg;
                   str2=(String)s2.m_ctg;
                   result=str1.compareTo(str2);
                   break;
                   case 10: //augments
                   i1 =s1.m_augmen.intValue();
                   i2 =s2.m_augmen.intValue();
                   result = i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
                   break;
                   case 11: //vendor
                   str1=(String)s1.m_vendor;
                   str2=(String)s2.m_vendor;
                   result=str1.compareTo(str2);
                   break;
         if (!m_sortAsc) result = -result;
         return result;
         public boolean equals(Object obj) {
              if (obj instanceof TrunkComparator) {
                   TrunkComparator compObj=(TrunkComparator) obj;
                   return (compObj.m_sortCol == m_sortCol) &&
                        (compObj.m_sortAsc==m_sortAsc);
              return false;
    }

Maybe you are looking for