Updating a jTable depending on a jTextField content ! :D

Hi to all !!!. I thought I'd never recover my password back but well here I am...
My name is Agustin and I am from Argentina... I am studying system engineering at: www.frc.utn.edu.ar and I have the following problem: I promoted a subject and they told me I could make a project about something we haven't seen on the signature's programs...
The other day I have this crazy idea... Hope someone can help me; this is what I need !:
Let's suppose we have this names on a certain dataBase and that we have in our JFrame a jTextField and a jTextArea aside a jTable... What I want is this:
If I haven't enter anyting in the jTextField1,i should get this on the jTable:
Agustin
Agger
Anastasia
Arnaldo
Banus
Bestia
Cardeilhac
If I enter "a/A" in the jTextField, I should get in the jTable:
Agustin
Agger
Anastasia
Arnaldo
And if I enter "Ag" or sopmething in the way, I should get in the jTable:
Agustin
Agger
Obviously I would like to know if can reverse it; I mean... If I delete from "Ag" the "g" letter, I'd like to get:
Agustin
Agger
Anastasia
Arnaldo
Is this possible ???. What listener should I add to the jTextField ? or what algorithms should I consider ?.
I hope I explain myself crearly... Thankx u very much...

Sun's Java Tutorial has a very complete discussion of tables. You should find the TableFilterDemo example very close to, if not exactly, what you want.
[http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]

Similar Messages

  • How to Update the JTable Content

    Hi Friends
    In my Program i have a Form having a JTable with shows some content on it. Now when the User Click on the Row it will ask where he wants to Edit that rows content. If the User gives Yes. then the Another JDialog opens with the Selected rows Data.
    Now when the User makes changes in the Data and Clicks on the Edit Button. It Should Show the Entered Data on the JTable immediatly.
    I am Posting my working Code. It works fine. But only the Updating the Newly entered Data to the JTable is not done.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class EditTable extends JDialog implements ActionListener,MouseListener
         private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
         private ButtonGroup bg;
         private JPanel exportpanel;
         private JButton btnExpots;
         JTable table;
         JScrollPane scroll;
         public EditTable()throws Exception
              setSize(550,450);
              setTitle("Export Results");
              this.setLocation(100,100);
              String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
              String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0203","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0204","PRIAM","SELVI","1354"},
                               {"B0205","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0207","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0208","PRIAM","SELVI","1354"}};
              btnExpots= new JButton("Export");
              btnExpots.addActionListener(this);
              btnExpots.setBounds(140,200,60,25);
              table = new JTable();
              table.addMouseListener(this);
              scroll=new JScrollPane(table);
              ((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
              System.out.println(table.getModel());
              exportpanel= new JPanel();
              exportpanel.add(btnExpots,BorderLayout.SOUTH);
              exportpanel.add(scroll);
              getContentPane().add(exportpanel);
              setVisible(true);
          public void actionPerformed(ActionEvent ae)
         public static void main(String arg[]) throws Exception
              EditTable ex= new EditTable();
           public void mouseClicked(MouseEvent me)
              Object obj=me.getSource();
              if(obj==table)
                        JTable source=(JTable)me.getSource();
                        int row = source.rowAtPoint(me.getPoint());
                        int column = source.columnAtPoint(me.getPoint());
                        System.out.println("Working Point"+row+"and"+column);
                        Object value1 = source.getValueAt(row,0);     
                        Object value2 = source.getValueAt(row,1);
                        Object value3 = source.getValueAt(row,2);
                        Object value4 = source.getValueAt(row,3);
                        String bkId=value1.toString();
                        String bkNm=value2.toString();
                        String bkAuthr=value3.toString();
                        String bkAuthrCd=value4.toString();
                        int opt = JOptionPane.showConfirmDialog(this,"Do you Really Want to Edit this Book?","Edit Books",JOptionPane.YES_NO_OPTION);
                        if(opt==JOptionPane.YES_OPTION)
                             try
                                  editForm  editfrm= new editForm ();
                                  editfrm.setVisible(true);
                                  editfrm.setVisible(true);
                                  editfrm.txtbookID.setText(""+bkId);
                                  editfrm.txtbookName.setText(""+bkNm);
                                  editfrm.txtbookAuthorName.setText(""+bkAuthr);
                                  editfrm.txtPrice.setText(""+bkAuthrCd);
                             catch(Exception ex)
                                  ex.printStackTrace();
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
    class editForm extends JDialog implements ActionListener
         JLabel lblbookID,lblbookName,lblbookAuthorName,lblPrice;
         JTextField txtbookID,txtbookName,txtbookAuthorName,txtPrice;
         JButton btnEdit,btnClose;
         JPanel editPanel;
              public editForm()
                   setSize (350,400);
                   this.setTitle("Edit Books");
                   this.setLocation(100,135);
                   lblbookID= new JLabel("Book ID:");
                   lblbookID.setBounds (15, 15, 100, 20);
                   lblbookName= new JLabel("Book Name:");
                   lblbookName.setBounds (15, 45, 100, 20);
                   lblbookAuthorName= new JLabel("Author Name:");
                   lblbookAuthorName.setBounds (15, 75, 100, 20);
                   lblPrice= new JLabel("Price:");
                   lblPrice.setBounds (15, 105, 100, 20);
                   Font fnt = new Font("serif",Font.BOLD,18);
                   txtbookID= new JTextField();
                   txtbookID.setFont(fnt);
                   txtbookID.setEditable(false);
                   txtbookID.setBounds (120, 15, 175, 20);
                   txtbookName= new JTextField();
                   txtbookName.setFont(fnt);
                   txtbookName.setBounds (120, 45, 175, 20);
                   txtbookAuthorName= new JTextField();
                   txtbookAuthorName.setFont(fnt);
                   txtbookAuthorName.setBounds (120, 75, 175, 20);
                   txtPrice= new JTextField();
                   txtPrice.setFont(fnt);
                   txtPrice.setBounds (120, 105, 175, 20);
                   btnEdit = new JButton("Edit");
                   btnEdit.addActionListener(this);
                   btnEdit.setBounds (50, 295, 100, 25);
                   btnEdit.setMnemonic(KeyEvent.VK_E);
                   btnClose= new JButton("Close");
                   btnClose.addActionListener(this);
                   btnClose.setBounds (170, 295, 100, 25);
                   btnClose.setMnemonic(KeyEvent.VK_C);
                   editPanel = new JPanel();
                   editPanel.setLayout(null);
                   editPanel.add(lblbookID);
                   editPanel.add(lblbookName);
                   editPanel.add(lblbookAuthorName);
                   editPanel.add(lblPrice);
                   editPanel.add(txtbookID);
                   editPanel.add(txtbookName);
                   editPanel.add(txtbookAuthorName);
                   editPanel.add(txtPrice);
                   editPanel.add(btnEdit);
                   editPanel.add(btnClose);
                   getContentPane().add(editPanel);
                public void actionPerformed(ActionEvent ae)
    }Could anyone Please Run my code and Help me to Update the JTable Record.
    Thank you for your Help
    Cheers
    Jofin

    Your EditForm needs acces to the TableModel and the current row you are editing. Then when the user clicks the save button you simply use the TableModel.setValueAt(...) method to update the model and the table will be repainted automatically.

  • Changing a row colour in JTable, depending on a column value

    Hi,
    I need assistance with the following:
    I need to change the colour of a row in a JTable, depending on a column value. I have been successful on changing one column's colour in each cell, depending on the value by using a CellRenderer extending DefaultTableCellRenderer.I am unable to set the other 2 columns's cell's depending on the first column value's.
    I would appreciate any help, source would be a bonus.
    Thx
    Charl

    Ok, here follows the code as requested. Note that this is the code setting each row in one of my columns depending on the value. Now i have to cgange column0 and column1 's foreground the same as what this column (column2) 's foreground is. Thx
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class ColorizedCell extends DefaultTableCellRenderer {
    static Hashtable cache;
    static {
    cache = new Hashtable();
    cache.put ("Device Responding to Poll",Color.green);
    cache.put ("Wan link Recovered",Color.green);
    cache.put ("No Response to Device Poll",Color.yellow);
    cache.put ("Wan Link Failure",Color.red);
    cache.put ("Lan Link Failure down",Color.red);
    cache.put ("Device Down",Color.red);
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected,
    boolean hasFocus, int row, int column)
    JLabel label = (JLabel) super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    label.setText((String)value);
    if(column == 2) {
    //setFont(bold);
    Color c = (Color)cache.get(value);
    label.setForeground(c);
    if (isSelected) {
    label.setOpaque(true);
    label.setBackground(Color.white);
    else {
    //setFont(plain);
    label.setForeground(Color.white);
    return label;
    }

  • Updating a JTable when using an AbstractTableModel

    Hi,
    I have tried to create a JTable with an AbstractTableModel but I am obviously missing something in all the tutorials and examples as I cannot get the table to update when using my model.
    My application reads data in from a CSV file that is selectable at run time, but I have written a small app that demonstrates the problem I am having.
    If you uncomment the DefaultTableModel lines of code all is OK, but I need to use my Abstract Class as I intend to colour certain rows and add a Boolean column, that I would like to display as a CheckBox and not just the String representation.
    Any help would be great as I am tearing my hair out here!!
    My Test Class
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class TestTable extends JFrame implements ActionListener
    private JPanel jpTestTable = new JPanel();          
    private Vector vColumnNames = new Vector();
    private Vector vCellValues = new Vector();
    private DefaultTableModel dtmTestTable;
    private CustomTableModel ctmTestTable;
    private JTable jtTestTable;
    private JScrollPane jspTestTable;
    private JButton jbGo = new JButton();
         public TestTable()
         dtmTestTable = new DefaultTableModel();
         ctmTestTable = new CustomTableModel();
         //jtTestTable = new JTable( dtmTestTable );  //using this instead of my CustomModel works fine
         jtTestTable = new JTable( ctmTestTable );
         jtTestTable.setAutoCreateRowSorter(true);
         jtTestTable.setFillsViewportHeight( true );
         jspTestTable = new JScrollPane( jtTestTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         jspTestTable.setBounds( 10, 10, 350, 400 );
         jspTestTable.setBorder( BorderFactory.createLoweredBevelBorder() );
         jbGo.setText( "Go" );
         jbGo.setBorder( BorderFactory.createRaisedBevelBorder() );
         jbGo.setBounds( 125, 430, 100, 25 );
         jbGo.addActionListener(this);
         jpTestTable.setLayout( null );
         jpTestTable.setBounds( 0, 0, 375, 500 );     
         jpTestTable.add( jspTestTable );
         jpTestTable.add( jbGo );
         this.setTitle( "Test Table" );
         this.getContentPane().setLayout( null );
         this.setBounds( 200, 50, 375, 500 );
         this.getContentPane().add( jpTestTable );
         this.setResizable( false );
         public void actionPerformed( ActionEvent e )
         updateTable();
         public void updateTable()
         vColumnNames.add( "Please" );
         vColumnNames.add( "work" );
         vColumnNames.add( "you" );
         vColumnNames.add( "git!" );
         vColumnNames.trimToSize();
         Vector vRow = new Vector();
              for( int i = 0; i < 10; i++ )
                   for( int x = 0; x < vColumnNames.size(); x++ )
                        vRow.add( "" + i + "" + x );
              vCellValues.add( vRow );
         //dtmTestTable.setDataVector( vCellValues, vColumnNames );  //using this instead of my CustomModel works fine
         ctmTestTable.setDataVector( vCellValues, vColumnNames );
         public void processWindowEvent(WindowEvent e)
         super.processWindowEvent(e);
              if(e.getID() == WindowEvent.WINDOW_CLOSING)
              exit();
         public void exit()
         System.exit( 0 );     
         public static void main(String args[])
         TestTable tt = new TestTable();
         tt.setVisible( true );
    }And my CustomTableModel Class
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.util.*;
    public class CustomTableModel extends AbstractTableModel
    protected Vector columnIdentifiers  = new Vector();
    protected Vector dataVector = new Vector();
         public CustomTableModel()
         public CustomTableModel( Vector data, Vector columnNames )
         setDataVector( data, columnNames );
         public int getColumnCount()
         return columnIdentifiers.size();
         public int getRowCount()
         return dataVector.size();
         public String getColumnName( int col )
         return "" + columnIdentifiers.get( col );
         public Object getValueAt( int row, int col )
         Vector vRow = new Vector();
         vRow = (Vector) dataVector.get( row );
         return (Object) vRow.get( col );
         public Class getColumnClass(int c)
         return getValueAt(0, c).getClass();
         public boolean isCellEditable(int row, int col)
              if (col < 2)
                   return false;
              else
                   return true;
         public void setValueAt( Object value, int row, int col )
         Vector vTemp = (Vector) dataVector.get( row );
         Vector<Object> vRow = new Vector<Object>();
              for( int i = 0; i < vTemp.size(); i++ )
                   vRow.add( (Object) vTemp.get( i ) );
         vRow.remove( col );
         vRow.add( col, value );
         vRow.trimToSize();     
         dataVector.remove( row );
         dataVector.add( row, vRow );
         dataVector.trimToSize();
         fireTableCellUpdated(row, col);
         public void setDataVector( Vector data, Vector columnNames )
         columnIdentifiers  = (Vector) columnNames.clone();
         dataVector = (Vector) data.clone();
         fireTableDataChanged();
    }I have just tried adding the following code after reading another example, but same result - arrrrrrrgggggggghhhhhhhhh!!!!
    ctmTestTable = (CustomTableModel) jtTestTable.getModel();
    ctmTestTable.fireTableDataChanged();Edited by: Mr_Bump180 on Jul 28, 2008 2:51 PM

    Hi camickr,
    Well that is good news as my Abstact class is about as much good as an ashtray on a motorbike. I think I must have misread or misunderstood the Table Tutorials as I thought I had to use an Abstrat class to get colurs based on conditions and to get Check Boxes to represent Boolean variables.
    I am clearly struggling with this concept - which I have never used before - do you know of any tutorials, that explain how to update a JTable with file data at runtime, as all the ones I have looked at set it as part of the java code - which is no good to me.
    Also am I overriding the DefaultTableModel Class correctly - I have written a seperate Model class but wounder if I need to include it in with my JTable class. I was trying to make it generic so I didn't have to write one for each JTable - but as I can't get it to work I should perhaps try to walk before I run.
    I'm not asking for the code, but just a guide to how close I am to where I want to be, and some links to tutorials that are closer to what I want to achieve. I will reread the Java Table Tutorial tonight - and you never know the penny may drop all on it's own this time!!!
    Thanks

  • The Apple Mac Store is re-downloading and reinstalling the update called "Final Cut Pro X Supplemental Content" literally everyday.

    My problem:  The Apple Mac Store is re-downloading and reinstalling the update called "Final Cut Pro X Supplemental Content" literally everyday.  I have a Mac Pro with Mavericks and Final Cut Pro X 10.1 installed.  It seems to complete the update to the best of my knowledge.  It shows it to be Final Cut Pro X Supplemental Content 1.0.  Is there a later version (a 2.0?)?  It seems it started when Mavericks updated.  Anyone else have this issue or know a solution to get it to update once and for all?

    hahah yeah i quit torrenting i have nothing but legit apps now.
    hope apple heard that!!!!
    your post fixed my issue
    but it did take more than deleting torrented apps, once your run a program with a MASReciept with someone elses Apple ID. that other ID is saved in all apps you got off of app store.
    You have to delete all apps that contain the MASReciept (the terminal command tells you which ones) then quit appstore then reboot download all apps again.
    it taught me to just buy my apps..

  • Updating a JTable by hiding/displaying columns

    I have a customizable JTable where I display/hide columns according to a users' selection criteria. My code works fine for hiding/displaying columns if the Jtable is opened for the fist time, but doesnot work if I want to hide columns in already displayed table.How do I do it?? Any clue?? I tried
    myTabModel.fireTableDataChanged();
    but this only works for updating the table data...it does not hide columns for me... when I hide column I just remove desired column like this:
    myTable.removeColumn(myTable.getColumn("Column 3"));

    Here is the sample code I tried. It worked without any invalidate or repaint or updateUI(). generated using NetBeans
    check for <==== for the line of code doing this
    * TableTest.java
    * Created on October 9, 2002, 1:42 PM
    * @author  Anki Reddy Nelaturu
    public class TableTest extends javax.swing.JFrame {
        /** Creates new form TableTest */
        public TableTest() {
            initComponents();
        /** 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.
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jButton1 = new javax.swing.JButton();
            jTextField1 = new javax.swing.JTextField();
            menuBar = new javax.swing.JMenuBar();
            fileMenu = new javax.swing.JMenu();
            openMenuItem = new javax.swing.JMenuItem();
            saveMenuItem = new javax.swing.JMenuItem();
            saveAsMenuItem = new javax.swing.JMenuItem();
            exitMenuItem = new javax.swing.JMenuItem();
            editMenu = new javax.swing.JMenu();
            cutMenuItem = new javax.swing.JMenuItem();
            copyMenuItem = new javax.swing.JMenuItem();
            pasteMenuItem = new javax.swing.JMenuItem();
            deleteMenuItem = new javax.swing.JMenuItem();
            helpMenu = new javax.swing.JMenu();
            contentsMenuItem = new javax.swing.JMenuItem();
            aboutMenuItem = new javax.swing.JMenuItem();
            getContentPane().setLayout(null);
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(80, 30, 230, 120);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton1.setBounds(170, 180, 81, 26);
            jTextField1.setText("jTextField1");
            getContentPane().add(jTextField1);
            jTextField1.setBounds(60, 190, 63, 20);
            fileMenu.setText("File");
            openMenuItem.setText("Open");
            fileMenu.add(openMenuItem);
            saveMenuItem.setText("Save");
            fileMenu.add(saveMenuItem);
            saveAsMenuItem.setText("Save As ...");
            fileMenu.add(saveAsMenuItem);
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    exitMenuItemActionPerformed(evt);
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            editMenu.setText("Edit");
            cutMenuItem.setText("Cut");
            editMenu.add(cutMenuItem);
            copyMenuItem.setText("Copy");
            editMenu.add(copyMenuItem);
            pasteMenuItem.setText("Paste");
            editMenu.add(pasteMenuItem);
            deleteMenuItem.setText("Delete");
            editMenu.add(deleteMenuItem);
            menuBar.add(editMenu);
            helpMenu.setText("Help");
            contentsMenuItem.setText("Contents");
            helpMenu.add(contentsMenuItem);
            aboutMenuItem.setText("About");
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            pack();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jTable1.removeColumn(jTable1.getColumnModel().getColumn(Integer.parseInt(jTextField1.getText())));        // <========
        private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
            System.exit(0);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new TableTest().show();
        // Variables declaration - do not modify
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JButton jButton1;
        private javax.swing.JMenuItem saveAsMenuItem;
        private javax.swing.JMenuItem saveMenuItem;
        private javax.swing.JMenuItem copyMenuItem;
        private javax.swing.JMenuItem pasteMenuItem;
        private javax.swing.JMenuItem cutMenuItem;
        private javax.swing.JMenuItem openMenuItem;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenu editMenu;
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JMenuItem contentsMenuItem;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JMenuItem deleteMenuItem;
        private javax.swing.JTable jTable1;
        // End of variables declaration
    }

  • Updating a Jtable

    Hi,
    im trying to do a music library that connects to mysql.
    My problem is that I dont know how to updatethe table after I have been modifying the database.
    Ex.
    I want to be able to import information to my database and then I want to see the changes instantly.
    At the moment I only see the changes after a restart of the program.
    My code:
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Dimension;
    import functions.*;
    public class MusicLibrary extends JFrame implements ActionListener
         //DEFENITIONS
         JLabel north, south, deepSouth;
         JScrollPane scrollPane,scrollPane2;
         ImageIcon background,top,bottom;
         JTextField searchField;
         JButton searchButton;
         JTable table;
         JMenuBar menuBar;
         JMenu file;
         JMenuItem importSong,removeSong,close;
         Container c;
         public MusicLibrary()
              //MENU
              menuBar = new JMenuBar();
              file = new JMenu("File");
              file.setMnemonic(KeyEvent.VK_F);
              importSong = new JMenuItem("Import Song", KeyEvent.VK_I);
              removeSong = new JMenuItem("Remove Song", KeyEvent.VK_R);
              close = new JMenuItem("Close",KeyEvent.VK_C);
              setJMenuBar(menuBar);
              menuBar.add(file);
              file.add(importSong);
              file.add(removeSong);
              file.addSeparator();
              file.add(close);
              //SOUTH
              background = new ImageIcon("background.gif");
              south = new JLabel (background);
              //NORTH
              top = new ImageIcon("top.gif");
              north = new JLabel(top);
              north.setLayout(new FlowLayout());
              north.setBackground(new Color(0,0,0));
              searchField = new JTextField(50);
              searchButton = new JButton("Search");
              north.add(searchField);
              north.add(searchButton);
              //CONTAINER
              c = getContentPane();
              c.setLayout(new BorderLayout());
              c.add(north, BorderLayout.NORTH);
              setSize(800,620);
              setVisible(true);
              setResizable(false);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              //DEEP SOUTH
              bottom = new ImageIcon("bottom.gif");
              deepSouth = new JLabel(bottom);
              c.add(deepSouth, BorderLayout.SOUTH);
              //LISTENERS
              close.addActionListener(this);
              //searchField.addActionListener(this);
              searchButton.addActionListener(this);
              importSong.addActionListener(this);
              //DATABASE CONNECTION
              try {
                   // load driver, create connection and statement
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                   Statement stmt = con.createStatement();
                   // query database
                   ResultSet rs = stmt.executeQuery("SELECT * FROM song");
                   // display result
                   getTable(rs);
                   scrollPane = new JScrollPane(table);
                   c.add(scrollPane, BorderLayout.CENTER);
                   // close statement and connection
                   stmt.close();
                   con.close();
              catch (ClassNotFoundException e) {
                   JOptionPane.showMessageDialog(null, e.toString(),
                        "ClassNotFoundException", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              catch (SQLException e) {
                   JOptionPane.showMessageDialog(null, e.toString(),
                        "SQLException", JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              //addWindowListener(new WindowHandler());
              setVisible(true);
         public void actionPerformed (ActionEvent e)
              if(e.getSource()==close)
                   System.exit(0);
              else if(e.getSource()==searchButton)
                   String textsearch = searchField.getText();
                   JOptionPane.showMessageDialog(null,"You searched for " + textsearch);
                   try {
                        // load driver, create connection and statement
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                        Statement stmt = con.createStatement();
                        // query database
                        ResultSet rs = stmt.executeQuery("SELECT * FROM song WHERE Song_Name = 'Africa'");
                        // display result
                        getTable(rs);
                        stmt.close();
                        con.close();
                   catch (ClassNotFoundException f) {
                        JOptionPane.showMessageDialog(null, f.toString(),
                             "ClassNotFoundException", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                   catch (SQLException f) {
                        JOptionPane.showMessageDialog(null, f.toString(),
                             "SQLException", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
              else if(e.getSource()==importSong)
                   try
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        Connection con = DriverManager.getConnection("jdbc:odbc:XXX);
                        EditDatabase.importMp3(con);          
                        //TEST
                        Statement stmt = con.createStatement();
                        // query database
                        ResultSet rs = stmt.executeQuery("SELECT * FROM song");
                        // display result
                        getTable(rs);
                        stmt.close();
                        con.close();
                   catch (Exception q){System.out.println("error" + q);}
              repaint();
         private void getTable(ResultSet rs) throws SQLException
              ResultSetMetaData rsmd = rs.getMetaData();
              Vector cols = new Vector();
              Vector rows = new Vector();
              // get column names
              for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                   cols.addElement(rsmd.getColumnName(i));
              // get rows
              while (rs.next()) {
                   Vector nextRow = new Vector();
                   for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        nextRow.addElement(rs.getString(i));
                   rows.addElement(nextRow);
              // create table
              table = new JTable(rows, cols);
         //-WINDOW HANDLER-
         private class WindowHandler extends WindowAdapter
              public void windowClosing(WindowEvent e)
                   System.exit(0);
         //-MAIN-
         public static void main (String[] arg)
              new MusicLibrary();
    *Functions is a package containing importMp3 and deleteMp3
    I really appreciate all the help I can get!

    Thanks for poiting in the right direction.
    I had to rethink the design and I stumbled upon some code of yours camickr, thanks.
    Now the code looks like this:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import functions.*;
    public class TableFromDatabase extends JFrame implements ActionListener, TableModelListener
         String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
         String url = "jdbc:odbc:mild";  // if using ODBC Data Source name
         String userid = "frenkan";
         String password = "tfb";
         Container c;
         JTable table;
         JScrollPane scrollPane;
         JMenuItem      importSong,
         removeSong,
         close;
         Connection connection;
         public TableFromDatabase()
              Vector columnNames = new Vector();
              Vector data = new Vector();
              try
                   //  Connect to the Database               
                   Class.forName( driver );
                   Connection connection = DriverManager.getConnection( url, userid, password );
                   //  Read data from a table
                   String sql = "Select * from Song";
                   Statement stmt = connection.createStatement();
                   ResultSet rs = stmt.executeQuery( sql );
                   ResultSetMetaData md = rs.getMetaData();
                   int columns = md.getColumnCount();
                   //  Get column names
                   for (int i = 1; i <= columns; i++)
                        columnNames.addElement( md.getColumnName(i) );
                   //  Get row data
                   while (rs.next())
                        Vector row = new Vector(columns);
                        for (int i = 1; i <= columns; i++)
                             row.addElement( rs.getObject(i) );
                        data.addElement( row );
                   rs.close();
                   stmt.close();
              catch(Exception e)
                   System.out.println( e );
              // Create TableModel with databases data
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              //model.addTableModelListener(this);
              //  Create table with model as TableModel
              table = new JTable(model)
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              JPanel buttonPanel = new JPanel();
              c = getContentPane();
              c.add( buttonPanel, BorderLayout.SOUTH );
              //MENU
              JMenuBar menuBar = new JMenuBar();
              JMenu file = new JMenu("File");
              importSong = new JMenuItem("Import Song");
              removeSong = new JMenuItem("Remove Song");
              close = new JMenuItem("Close");
              importSong.addActionListener(this);
              removeSong.addActionListener(this);
              close.addActionListener(this);
              setJMenuBar(menuBar);
              menuBar.add(file);
              file.add(importSong);
              file.add(removeSong);
              file.addSeparator();
              file.add(close);
         public void tableChanged(TableModelEvent e)
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == close)
                   System.exit(0);
              else if (e.getSource() == importSong)
                   try
                        //  Connect to the Database               
                        Class.forName( driver );
                        Connection connection = DriverManager.getConnection( url, userid, password );
                        EditDatabase.importMp3(connection);
                   catch (Exception exception)
                        System.out.println("Fel: " + exception);
         public static void main(String[] args)
              TableFromDatabase frame = new TableFromDatabase();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }Basicly the same as your with some few modifications.
    What I want to know is how to update the table after I have imported a song to the database thru my importMp3() function? Please respond on a basic level. Any help is much appreciated!

  • Dynamically Updating a JTable

    I am developing an EPOS system using java, that uses a JTable to display the recipt, before it is printed.
    I have a class for the recipt data, stored in a vector which works and using observers fires events to the gui when things are added etc. My problem comes when i try to dynamically change the tables content, my idea was to create a new table, fill it with the new data, set the scroll pane around the new table and call revalidate to show the new table.
    This is possible but seems far too much work to just update a table! I would also assume the amount of extra garbage collection would require extra processing that seems pointless.
    Is there another way i could do it? Ideally i just want to refresh the content in the table for each update sent by the observable.
    Thanks

    Make your TableModel observe your observable and update it's contents. Remember to fire the appropriate event after the update.

  • AbstractTableModel not updating the JTable...

    I need to fix this probelm very urgently... Running out of time...
    Pleas see the code below. I am trying to add a new row to the JTable using two classes. as given below...
    Problem:-
    1) Any new row added is getting added to the first row and the table always shows only the recently added record (at first row).
    2)."public synchronised void updatePlayer(String[] ptyprrecord)" Method in PTypeInfoModel is giving problem in firing table change...
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.table.TableColumn;
    public class SerjProType {
    public JTable ProTypeTable;
    public String ColumnNames[];
    public String DataValues[][];
    public JFrame jframe;
    public PTypeInfoModel ProInfoModel;
    public int rownum = 0;
    public String[] data = new String[4];
    /** Creates a new instance of SerjProType */
    public SerjProType() {        
    //createColumn();
    //createData();
    jframe = new JFrame(" Testing Abstract Table Model");
    ProInfoModel = new PTypeInfoModel();
    ProTypeTable = new JTable(ProInfoModel);
    TableColumn tc = null;
    for(int i=1;i<4;i++){
    tc = ProTypeTable.getColumnModel().getColumn(i);
    tc.setCellRenderer(new SummColmColorRenderer());
    ProTypeTable.setPreferredScrollableViewportSize(new Dimension(600, 200));
    ProTypeTable.setSelectionBackground(Color.lightGray);
    ProTypeTable.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
    if(e.getClickCount()==2){
    System.out.println("This is being clicked");
    new SerjInstDet();
    JScrollPane jsp = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jsp.getViewport().add(ProTypeTable);
    JButton fireRowbutton = new JButton("Fire Row Update...");
    fireRowbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){                   
    rownum++;
    data[0] = "PTYPEee"+rownum+" :-) ";
    System.out.println("Value of data[0] -- "+data[0]);
    data[1] = "12";
    data[2] = "13";
    data[3] = "13";
    ProInfoModel.updatePlayer(data);
    //add(fireRowbutton);
    JButton fireCellbutton = new JButton("Fire Cell Update...");
    fireCellbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
    //add(fireCellbutton);
    JPanel jpane = new JPanel();
    jpane.add(jsp);
    jpane.add(fireRowbutton);
    jpane.add(fireCellbutton);
    jframe.getContentPane().add(jpane);
    jframe.setSize(600,400);
    jframe.setVisible(true);
    //setSize(500,200);
    //show();
    //setTitle("Process Type");
    public static void main(String args[]){
    new SerjProType();
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    public class PTypeInfoModel extends AbstractTableModel {   
    protected static int NUM_COLUMNS = 4;
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String Ptype_name ="Process Type";
    static final public String Ok_Inst = "Ok";
    static final public String OnHold_inst = "On Hold";
    static final public String Late_Inst = "Late";
    protected Vector data = null;
    /** Creates a new instance of PTypeInfoModel */
    public PTypeInfoModel() {
    data = new Vector();
    public String getColumnName(int column) {
         switch (column) {
         case 0:
         return Ptype_name;
         case 1:
         return Ok_Inst;
         case 2:
         return OnHold_inst;
         case 3:
         return Late_Inst;
         return "";
    public synchronized int getColumnCount() {
    return NUM_COLUMNS;
    public synchronized int getRowCount() {
    if (numRows < START_NUM_ROWS) {
    return START_NUM_ROWS;
    } else {
    return numRows;
    public synchronized Object getValueAt(int row, int column) {
         try {
    String[] w = (String[])data.elementAt(row);
    switch (column) {
    case 0:
    return w[0];
    case 1:
    return w[1];
    case 2:
    return w[2];
    case 3:
    return w[3];
         } catch (Exception e) {
         return "";
    public synchronized void updatePlayer(String[] PTypeRecord) {     
    String PTypeName = PTypeRecord[0]; //find the Name
    String[] p = null;
    int index = -1;
    boolean found = false;
         boolean addedRow = false;
    int i = 0;
    int vecsize = data.size();
    if (vecsize == 0){}
    else{
    for (int l=0;l<vecsize;l++){
    String[] q = (String[])data.elementAt(l);
    for(int m=0;m<q.length;m++){
    System.out.println("Vector Content "+ q[m]);
    while (!found && (i < nextEmptyRow)) {
    p = (String[])data.elementAt(i);
    System.out.println("value of p[o] -- "+p[0]);
    System.out.println("value of PTypeName is -- "+PTypeName);
    String pofzero = p[0];
    if (PTypeName.equalsIgnoreCase(pofzero)) {
    found = true;
    index = i;
    } else {
    i++;
    if (found) { //update old player
         data.setElementAt(PTypeRecord, index);
    } else { //add new player
         if (numRows <= nextEmptyRow) {
              //add a row
    numRows++;
              addedRow = true;
    index = nextEmptyRow;
         data.addElement(PTypeRecord);
    nextEmptyRow++;
         //Notify listeners that the data changed.
         if (addedRow) {
         fireTableRowsInserted(index,index);
         } else {
         fireTableRowsUpdated(index, index);
    public synchronized void clear() {
         int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
         data.removeAllElements();
    nextEmptyRow = 0;
         if (oldNumRows > START_NUM_ROWS) {
         fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
         fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    My guess is that your variable "index" has a wrong value: toward the end, when you check the variable "addedRow", you use the variable "index" to notify which row was inserted/updated. However, I can see a few lines before that this very same variable, "index", is incremented even if "addedRow" has been set. Most probably, in the best case scenario, this variable will point 1 row too far.
    I haven't launched the program nor read it extensively, so it is more a quick guess than anything else. If it isn't the problem, I would advise you to check what exactly the program does at the end: is the variable "addedRow" set or not, does the variable "index" point to the right row, and if yes, is the event forwarded to the correct place, etc...

  • Update to iOS 4.2.1 deleted content and will not restore

    I just updated my IPod touch to the latest software using the same computer that I always use my iPod with and all of my content was deleted. I tried restoring from my last backup, which seems to be from February, and even after restoring everything is still gone. I am primarily concerned with my Nike+ workout history and my playlists. Any advice?

    - Were all the apps in the iTunes library? The iTunes backup does not inlcudd synced media like apps and music
    - Was the restore successful, that is it went though all the steps without errors?
    - Did anything get restored?
    - Try restoring again.

  • How do I update a JTable immediately after editing a cell?

    I have a JTable where I use a JComboBox to select a value in a cell. When a value is selected this updates another cell in the JTable.
    This works like I want to except for that I have to deselect the JComboBox (ie. click in another cell) before the other cell is updated.
    I want the cell to be updated when the JComboBox changes without having to deselect the JComboBox first.
    How can I do this?
    Thanks in advance for any help...
    Geir

    As an example I just copied the TableRenderDemo from the Swing-tutorial (http://java.sun.com/docs/books/tutorial/uiswing/components/table.html).
    The only change I have made to the TableRenderDemo is to replace the DefaultCellEditor with my own editor (ComboBoxEditor extends DefaultCellEditor).
    The only change I have made to the program itself is therefore to replace
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));*
    with
    sportColumn.setCellEditor(new ComboBoxEditor());*
    (And add the class ComboBoxEditor, of course.)
    When you run the original program, the default editor closes itself when a value is selected from the combobox. My editor doesen't close itself when a value is selected, but remais open until you click on another tablecell. I want my editor to close itself in the same way the DefaultCellEditor does.
    The code for TableRenderDemo is here: http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TableRenderDemoProject/src/components/TableRenderDemo.java
    Again, to test what I mean just replace
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));*
    with
    sportColumn.setCellEditor(new ComboBoxEditor());*
    (And here is the code for my own celleditor:)
    private class ComboBoxEditor extends DefaultCellEditor {
    private JComboBox comboBox = null;
    public ComboBoxEditor(){
    super(new JComboBox());
    @Override public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,int row, int column){
    comboBox=new JComboBox();
    String name=(String)table.getValueAt(row,0);
    if(name.equals("Mary")){
    comboBox.addItem("Marys sport");
    comboBox.addItem("Marys cooking");
    else{
    comboBox.addItem("Other sport");
    comboBox.addItem("Other cooking");
    return comboBox;
    //else return super.getTableCellEditorComponent(table,value,isSelected,row,column);
    public void setCellEditorValue(Object newData){
    comboBox = (JComboBox) newData;
    @Override public Object getCellEditorValue(){
    return comboBox;
    }//end class

  • Updating a JTable using CachedRowSet data

    Hello, I would like to know how I can update my already created JTable receiving data from a CachedRowSet without creating a new table model (this is the method I have been using). I have read about using the fireTableDataChanged() method but I cant figure out how to use this works. Maybe an explanation on how the information in the CachedRowSet is updated in the JTable when notifiers are used will help.
    Any help will be appreciated

    camickr wrote:
    table.setAutoCreateColumnsFromModel( false );
    Perfect. This works well for my issue. I can now use the setModel() method without having the columns reordered.Damn camickr, that is a bloody good thing to know (it's often so much easier to recreate the table model, here's a very neat solution to one of the pitfalls)! Thanks :)
    Since this is solved, I still want to know how I can use the fireTableDataChanged() method and AbstractTableModel interface with CachedRowSet (just out of curiosity). I have been looking through jduprez's suggestion to figure this out too. I am currently faced with the issue,
    I have two classes, one for the CachedRowSet and the other with the table implementationsAs you describe it, I don't think that's a good approach: what I meant wad an implementation of TableModel , not a subclass of JTable : the stock JTable already knows how to work with any model implementation, as long as it implements TableModel .
    Where do I need to use the AbstractTableModel interface?It is a class, not an interface: it implements TableModel and provides useful defaults for some methods (at least, the management of the list of TableModelListener )
    My suggestion was that you define a custom class that extends AbstractTableModel , and uses its fireXxx judiciously.
    here is an example:
    public class RowSetAwareTableModel extends AbstractTableModel {
        public void setUpdateddata(RowSet newData) {
            this rowSet = newdata;
            super.fireTabledataChanged();
        /** Implementation of TableModel */
        public int getRowCount() {
            return rowset.getMaxRows();
        // etc...
    }

  • Updating a JTable using a JTable

    I am looking to update an empty JTable using the data from a JTable containing a set of data.
    I am aware that addRow can be used with the DefaultTableModel from previous discussions on this forum, but I have found this call isn't available when using AbstractTableModel.
    The reason I have been having some problems with this as it is necessary for the AbstractTableModel to be used in the context of the GUI, and I am asking if there is a way to solve this using the AbstractTableModel?
    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.

    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.No you aren't. You can't create an Abstract class because not all the methods are implements. You are using a class that extends AbstractTableModel.
    So why not use the DefaultTableModel and make your life simple?

  • Updating a JTable with an array of values

    Ther is a constructor that allows for the cretion of the table with an iniital array of values. However subsequent updates of blocks of data- say you received an array of updated data form a database- reuiqre you to update ince cell at a time. Is ther any way fo updating a whole block at once. I should point out that I am asking this because I am using JTables in the Matlab programming environment where arrays are the basic unit and looping through is a comparatively slow process

    Yes, you can extend the AbstractTableModel and write a method for updating a whole block.
    lets say you've got a Vector with Float[] arrays as elements to hold a 2D array of Float. The you could write:
          TableModel dataModel = new AbstractTableModel() {
                public int getColumnCount() { return col_names.size(); }
                public int getRowCount() { return data.size();}
                public Object getValueAt(int row, int col) {
                   return ((Float)((Float[])data.elementAt(row))[col]).toString();
                public String getColumnName(int col) {
                 return ((String)col_names.elementAt(col));
                public Class getColumnClass(int col) {
                 return String.class;
                public boolean isCellEditable(int row, int col) {
                  return true;
                public void setValueAt(Object aValue, int row, int col) {
                   try {
                     Float fv = Float.valueOf((String)aValue);
                    ((Float[])data.elementAt(row))[col] = fv;
                   } catch (Exception ex) {
                public void setBlock(Float block[][], int row, int col) {
                   // copy the Arrays with System.arrayCopy into data
          };PS: I don't know, if the above is correct written, havn't test this. But I hope you can recognize the idea behind it.
    wami

  • Update rule not activating for Standard BI Content

    Dear Reader,
    I am unable to activate the BI Content update rule for sales cube. All the key figures listed in the update rule are RED.
    How can i fix this?
    Please advise.

    HI,
       This usually happens if if you have added new fields in the cube and if that field is not properly mapped , ie
    no mapping being done but it looks like some routine there for that field but we would have not written the routine
    just simply routine symbol appears in that case
    if you dont have mapping assign it as initial in update rule or map them properly which will resolve your issue.
    Thanks,
    Arun.

Maybe you are looking for

  • Want to play pre-intel game, got a PowerPC iMac and want to install OS 9, anything I need to know before hitting ebay?

    Found the pre-intel machine, but unfortunately (in this case) it is running OS 10.4.11. Want to make sure before I buy from ebay that I am getting the OS 9 I can use on this computer. Saw a reboot set for OS 9, will that work? Or do I need to already

  • Conditional Receiver Determination

    Hi Friends, From Proxy i send a field to XI. Using JDBC lookups i have mapped in such a manner that if the content of the particular field exists in the Oracle Table i send the incoming field content to receiver field. But incase the field doesn't ex

  • Xml files not available for import

    Is there a way to open xml files from fcp 7 in fcp x without purchasing the 3rd party ap 7 to x? I read that some of the past updates were supposed to resolve this issue but it has yet to work for me. I am runnin fcp x 10.0.7 on OS X 10.7.5. The file

  • Substitution for specific subpopulation

    Hi, Is there any method to delegate tasks for a set population (positions or sub org units)? My customer has an organization, where all managers have an assistant who can be appointed the responsability over a number of employees. For example, the ma

  • Missing presets

    Hi all, I am using GarageBand 09 and all was great until all of a sudden all of the factory compression/eq/reverb presets went missing. I logged into a different user and loaded GB and all the presets were there, but not in my main accout. Anyone kno