Update JTable GUI

hello,
i'm stuck with a stupid prob. i initialize my table with some number of row and cols. but after user finishes their drwaings i would to update my table GUI depending upon no of node they'll draw. and also i want to update the row contents dynamically. how can i do that. pls help..............................
thnx,
ar

i can update the table when i put on a frame but for my application i need to put the table on a panel I don't understand what you are saying and I can't guess what your code looks like so here's a working [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418866]example of adding/removing columns.

Similar Messages

  • Update JTable model col through header name in fast way

    old day, i update my JTable model through the way :
    tableModel.setValueAt(aValue, rowIndex, jTable1.getColumn("HeaderName").getModelIndex());now, i am adding a feature to my table, where the user can remove column.
    when user remove the column, is just the JTable GUI column being removed,. the underlining TableModel column is still there.
    my new feature will broke my above code.
    hence, i change my code to :
    for(columnIndex=0; columnIndex<columnCount; columnIndex++) {
         String name = tableModel.getColumnName(columnIndex)
         if(name.equals("HeaderName"))
              tableModel.setValueAt(aValue, rowIndex, columnIndex)
    }instead of looping through, is there any way i can retrieve the column model index in a fast way?
    a way i can think off, is inherit from DefaultTableModel, and add a map member, so that it can directly map the header name to col index.
    is there any better way?
    thanks

    i don't know why but the KeyListener does work fine with another application that i have also created Not a good solution. First of all the column still exists, so the user will tab from one column to your "hidden" column and wonder whats happening.
    The correct solution is to remove the TableColumn from the TableColumnModel. You can still access the data in the TableModel:
    table.getModel().getValueAt(...)
    No need to use the convertColumnIndexToModel.

  • Updating JTable from data from resultset

    I have an athletics database, where the user updates an event and round e.g. 100M run Round 1. I then have a query which returns the 3 fastest times from each round for whatever event.
    Now on my JTable gui, the user chooses what event and round to update through 2 JCombo boxes, one for events, one for rounds. Now if the user chooses the round name final, i need the JTable to update the table with the three fastest times from rounds 1, 2 and 3.
    Whats the best way to do this? I was thinking putting all the different result sets into an array, and then through an if loop have somthing like
    if(roundType.equals (final))then in the body of this loop, create an instance of my JTable setting the rows for each column the the resultset data.
    Is this the right approach or any other advise?
    cheers

    You probably defined the "table" variable twice. Once as a class variable and once as a local variable and your "insertValue" method is referring to the wrong variable and therefore updating the wrong table.

  • Updating a GUI component from a runnable class that doesn't know that GUI

    Hi. I have a problem that I think isn't solvable in an elegant way, but I'd like to get confirmation before I do it the dirty way.
    My application allows the user to save (and load) his work in sessions files. I implemented this by a serializable class "Session" that basically stores all the information that the user created or the settings he made in its member variables.
    Now, I obviously want the session files created by this to be as small as possible and therefore I made sure that no GUI components are stored in this class.
    When the user has made all his settings, he can basically "run" his project, which may last for a long time (minutes, hours or days, depending on what the user wants to do....). Therefore I need to update the GUI with information on the progress/outcome of the running project. This is not just a matter of updating one single GUI component, but of a dynamic number of different internal frames and panels. So I'd need a reference to a GUI component that knows all these subcomponents to run a method that does the update work.
    How do I do that? I cannot pass the reference to that component through the method's argument that "runs" the project, because that needs to be a seperate thread, meaning that the method is just the run() method of that thread which has no arguments (which I cannot modify if I'm not mistaken).
    So the only thing I can think of is passing the reference through the constructor of the runnable class (which in turn must be stored in the session because it contains critical information on the user's work). As a result, all components that need to be incorporated in that updating process would be part of the session and go into the exported file, which is exactly what I wanted to avoid.
    I hope this description makes sense...
    Thanks in advance!

    Thanks for the quick answer! Though to be honest I am not sure how it relates to my question. Which is probably my fault rather than yours :-)
    But sometimes all it takes me to solve my problem is posting it to a forum and reading it through again :)
    Now I wrote a seperate class "Runner" that extends thread and has the gui components as members (passed through its constructor). I create and start() that object in the run method of the original runnable class (which isn't runnable anymore) so I can pass the gui component reference through that run method's argument.
    Not sure if this is elegant, but at least it allows me to avoid saving gui components to the session file :-)
    I am realizing that probably this post shouldn't have gone into the swing forum...

  • Update Jtable from access database

    as the title suggests help me guys... till now i have a database and some contents in it.. when the application starts the table is filled with contents of the database.. now whenever i add or remove a row in the databse i want to show it in the table... i have a Vector called dbData with the present contents of the database.. i want to update jtable with contents of dbData.... how to do it??

    the best things i can see to do is
    JTable table = new Jtable(.....); // this was ur table before;
    deleteRow(table); // you deleted the row
    // now you have a vector containing all the data for the rows;
    // but you need a vector containing the columns for the rows too
    //so now you do
    table = new JTable(dbData,columnnames);
    repaint();dbData must be a vector of vectors;
    dbData.elementAt(1) return a vector with all the data for row one
    so dbData.elementAt(1).elementAt(1) will be the data for row 1 column 1
    // dbData will be the data still remaining in the table
    or instead of the above you could use a nested for loop and set each element one at a time
    Object temp;
    int numberofRows = dbData.elementCount();
    int numberofColumns = db.elementAt(0).elementCount();
    for(int row = 0; row < numberofColumns;row++)
    for( int column = 0; column < numberofRows; column++)
      temp = dbData.elementAt(row).elementAt(column);
      table.setValueAt(temp,row,column);
    }

  • Updating the GUI from a background Thread: Platform.Runlater() Vs Tasks

    Hi Everyone,
    Hereby I would like to ask if anyone can enlighten me on the best practice for concurency with JAVAFX2. More precisely, if one has to update a Gui from a background Thread what should be the appropriate approach.
    I further explain my though:
    I have window with a text box in it and i receive some message on my network on the background, hence i want to update the scrolling textbox of my window with the incoming message. In that scenario what is the best appraoch.
    1- Shall i implement my my message receiver as thread in which i would then use a platform.RunLater() ?
    2- Or shall i use a Task ? In that case, which public property of the task shall take the message that i receive ? Are property of the task only those already defined, or any public property defined in subclass can be used to be binded in the graphical thread ?
    In general i would like to understand, what is the logic behind each method ?
    My understanding here, is that task property are only meant to update the gui with respect to the status of the task. However updating the Gui about information of change that have occured on the data model, requires Platform.RunLater to be used.
    Edited by: 987669 on Feb 12, 2013 12:12 PM

    Shall i implement my my message receiver as thread in which i would then use a platform.RunLater() ?Yes.
    Or shall i use a Task ?No.
    what is the logic behind each method?A general rule of thumb:
    a) If the operation is initiated by the client (e.g. fetch data from a server), use a Task for a one-off process (or a Service for a repeated process):
    - the extra facilities of a Task such as easier implementation of thread safety, work done and message properties, etc. are usually needed in this case.
    b) If the operation is initiated by the server (e.g. push data to the client), use Platform.runLater:
    - spin up a standard thread to listen for data (your network communication library will probably do this anyway) and to communicate results back to your UI.
    - likely you don't need the additional overhead and facilities of a Task in this case.
    Tasks and Platform.runLater are not mutually exclusive. For example if you want to update your GUI based on a partial result from an in-process task, then you can create the task and in the Task's call method, use a Platform.runLater to update the GUI as the task is executing. That's kind of a more advanced use-case and is documented in the Task documentation as "A Task Which Returns Partial Results" http://docs.oracle.com/javafx/2/api/javafx/concurrent/Task.html

  • What is the best way to get another object's method to update my GUI?

    package stuff;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame{
      private static JButton ProcessButton = new JButton();
      private static JLabel jLabel2 = new JLabel();
      public static void main( String args []){
         Test f = new Test();
         f.setSize(500,500);
         Container c = f.getContentPane();
         ProcessButton.addActionListener( new ActionListener(){
                                     public void actionPerformed(ActionEvent e) {
                                        jLabel2.setText("Connecting to DB");
                                        //Connection connection = Tools.setUpConnectionToDB(url,userName,pwd);
         c.add(ProcessButton, BorderLayout.NORTH);
         jLabel2.setText("My Label");
         c.add(jLabel2, BorderLayout.SOUTH);
         f.setVisible(true);
    {\code]
    The method setUpConnectionToDB can take 1 - 10 mins to complete. By this time a user will prob have quit my app thinking
    it's crashed because it doesn't update the GUI with a progress status. :(
    What is the best way to get this method to update the GUI of the app which calls it?
    Something like  Connection connection = Tools.setUpConnectionToDB(url,userName,pwd, this);
    ie this being a reference to the GUI's JFrame is what I'm trying to use?

    A handy class to know about but not really what I'm after.
    I need the method call
    Tools.setUpConnectionToDB(url,userName,pwd);
    to be able to update a component ( The JLabel ) on the GUI
    Connection connection = Tools.setUpConnectionToDB(url,userName,pwd, this);
    [\code]
    method defn:public static Connection setUpConnectionToDB( String url, String user, String pwd, JFrame f ){
    //Why doesn't this code below modify the GUI on the calling App?
    f.jLabel2.setText("Setting UP DB Connection");
    f.repaint();
    Connection c = null;
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    c = DriverManager.getConnection(url,user,pwd);
    catch(ClassNotFoundException e){
    JOptionPane.showMessageDialog(null , "Error loading DB driver");
    System.exit(0);
    catch(Exception e){
    JOptionPane.showMessageDialog(null , "Error connecting to DB, check config file");
    System.exit(0);
    return c;
    }[\code]

  • How to update a GUI

    In the code below, how do I update the GUI with the random number that is generated? I cannot use a static method because I may need multiple instances of the GUI and each instance needs to have it's own unique output displayed. I can't combine the two class together because I want to serialize the Controller but NOT the GUI.
    public class Controller{
         public void makeNums(){
              // creates random numbers at random times
    public class Gui{
         private Controller control;
         public Gui(Controller control){
              this.control = control;
              openGui();                  // this method creates all the components of the GUI
              control.makeNums();
    }How can the Controller update the GUI after the random number has been generated?

    SquareBox wrote:
    DrClap wrote:
    It's pretty trivial:Thanks. I will give that a try. Just one final question here. Is it dangerous to use "this" in the Constructor? Thanks so much for the tip. I will give it a try right now.It's generally a bad idea to let the "this" reference escape from the c'tor before the object is fully initialized. You don't want some other class or method to be using your object before it's in a fully valid state. In this case, however, the object in question has already been fully initialized before you leak the reference, so you should be fine.
    Having said that, however, I'm not 100% sure that there's not a potential for memory inconsistency in a multithreaded context. I think in this particular case you're okay, but another approach might be to have an external method create the Gui and then call control.setGui(gui).

  • Clear and update JTable.

    Hi. this is a follow up from [Original Tread in "New To Java"|http://forums.sun.com/thread.jspa?messageID=10886612&#65533;]
    Hope you can help me here. For you who dont read the link. This application is build only to lay up here. So the Layout aint pretty. It compiles and run tho. What i want and cant get to work is to reload table when i push my JTabbedPane.
    Main Class
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        // clear and update JTable in class three
        public void clearThree() {
            Three t = new Three();
             t.clearVector();
        public JFrame frame() {
            JFrame frame = new JFrame();
            JTabbedPane tab = new JTabbedPane();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    clearThree();// this dont work
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }// class two
    package test;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    // class two&#347; only purpose is to  call clear() in class Three
    public class Two extends JPanel{
    public Two(){
    toolBar();
      public void clearThree () {
       Three t = new Three();
       t.clearVector();
      public void toolBar(){
      JToolBar bar = new JToolBar();
      JButton button = new JButton("clear");
      button.addActionListener(new ActionListener (){
          public void actionPerformed(ActionEvent e){
          clearThree(); // this dont work
    bar.add(button);
    add(bar);
    }// class three hold the table.
    package test;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    public class Three extends JPanel{ 
            DefaultTableModel model;
            JTable table;
            Vector v = new Vector();
            Vector a = new Vector();
            Vector<Vector> r = new Vector<Vector>();
        public Three() {
            jBar();
            jTable();
        public void clearVector(){
            v.removeAllElements();
            a.removeAllElements();
            r.removeAllElements();
            model.fireTableDataChanged();
        public void jBar() {
            JToolBar bar = new JToolBar();
            JButton button =  new JButton("clear");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    clearVector();// this does work
            bar.add(button);
            add(bar);
        public JScrollPane jTable(){
            v.addElement("ID");
            v.addElement("Name");
            a.addElement("01");
            a.addElement("Magnus");
            r.add(a);
            model = new DefaultTableModel(r,v);
            table = new JTable(model);
             JScrollPane pane = new JScrollPane(table);
             add(pane);
             return pane;
    }

    Thank you for your replay, I have taken all of your tips and modifed my original application. but the problem is still there. This has been a very messy thread. and it is becouse i thougth it were a table/model problem. But it&#347; not. In the code below I have a JTextField. When i push the JTabbedPanes i want the setText(); to kick in. this compile and run.
    // class One
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        public JFrame frame() {
            JTabbedPane tab = new JTabbedPane();
            final  Three t = new Three();
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                      t.setText(); // should call setText() in class Three.
            frame.add(panel);
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }class Two. Does nothing more then holding an empty tab
    package test;
    import javax.swing.*;
    public class Two extends JPanel{
    public Two(){
    emptyPane();
      public void emptyPane () {
      JLabel  label = new JLabel("Just an empty JTabbedPane");
      add(label);
      }class Three
    package test;
    import javax.swing.*;
    public class Three extends JPanel{ 
             JTextField text;
        public Three() {
            text();
        public void setText() {
            text.setText("Hello"); // this piece of code i want to insert in my JTextField
            validate();                // when i push the JTabbedPanes.
            repaint();
            updateUI();
        public JTextField text(){
             JToolBar bar = new JToolBar();
            text = new JTextField("",20);
            bar.add(text);
            add(bar);
            return text;
    }

  • How to force update jtable display

    I am trying to add some filtering funtionality to my swing application that uses a JTable. What I do is to filter the JTable's datamodel, and call repaint() on the jtable and JPanel, and do jframe.pack(); Sometimes it works, sometimes it doesn't. I check the jtable model, and it is being updated properly. I guess it is a GUI update problem. Is there a better way to force the whole app's GUI to be updated?
    //update tableModel
    //repaint() jtable;
    //repaint() jpanel;
    jf.pack();

    A couple questions
    1. Did you write your own table model? Not calling fireTableDataChanged() can cause problems in this case.
    2. Do you update the table from a thread? You might need to put the updates on the event thread (SwingUtilities.invokeNoow() or invokeLater()) or manually call fireTableDataChanged() (I'm not sure if this needs to happen on the event thread)

  • Dynamically Updating JTable, please help

    I am trying to create an GUI for a java program I wrote to interface with motes running TinyOS. I am having some serious problems creating this because in the JTable tutorial everything is static so I can't figure out how I'm supposed to modify the table from my code. I'm basically reading packets coming in from the serial port and updating several data fields based on what is contained in the packet. I want certain cells in the JTable to reflect the changes that occur in the variables I have, sort of like a debugger would display, but in real time and at full run speed. I tried using the setValueAt function but the problem is the JTable is created in a static method and so I cannot call it from main. I tried moving the section of code that monitors the serial port and updates my data to the createAndShowGUI function, but unfortunately the table will not display unless this function returns, but the program will never return from this function if I move the code there and so I just get a completely grey JTable displayed. I have included the code below, sorry for the length of it but I need some help on this one, I was never taught java and am trying to learn this on my own for research purposes. As it stands now the only error generated by this code is from the following line:
    newContentPane.DataTable.setValueAt("asdfsa",1,1);
    I am not allowed access to newContentPane because it has been dynamically instantiated by createAndShowGUI and I cannot access it through main.
    I'd appreciate any help on this, thank you.
    package net.tinyos.tools;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JComponent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Date;
    import java.io.*;
    import net.tinyos.packet.*;
    import net.tinyos.util.*;
    import net.tinyos.message.*;
    public class BeaconListen extends JPanel {
    private static int MAX_NODES = 10;
         JTable DataTable;
         public BeaconListen(){
         super(new GridLayout(1,0));     
         Object[] ColumnNames = {"Node","PPS","Average PPS","Time Elapsed"};
         Object[][] Data= {
         {"0","","",""},
         {"1","","",""},
         {"2","","",""},
         {"3","","",""},
         {"4","","",""},
         {"5","","",""},
         {"6","","",""},
         {"7","","",""},
         {"8","","",""},
         {"9","","",""},
         DataTable = new JTable(Data,ColumnNames);
         DataTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
         JScrollPane scrollPane = new JScrollPane(DataTable);
    add(scrollPane);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI(){
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("MoteData");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    BeaconListen newContentPane = new BeaconListen();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
         if (args.length > 0) {
         System.err.println("usage: java net.tinyos.tools.BeaconListen");
         System.exit(2);
         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();
                   PacketSource reader = BuildSource.makePacketSource();
         if (reader == null) {
         System.err.println("Invalid packet source (check your MOTECOM environment variable)");
         System.exit(2);
              int i, total = 0;
         int reset =1;
         int packetcount[] = new int[MAX_NODES];
         int PL[] = new int[MAX_NODES];
         int counter[] = new int[MAX_NODES];
         double RSSI[]= new double[MAX_NODES];
         int signalStrength=0;
         double strengthUnsigned=0;
         int Transition=0;
         int PPS=0;
         int FirstRun=1;
         int packetHold=0;
         double avgPacketCount[] = new double[MAX_NODES];
         int secondsElapsed=0;
         int averageReset=1;
         int totalPacketsReceived[] = new int[MAX_NODES];
         System.out.println("Node Listening");
         try {
         reader.open(PrintStreamMessenger.err);
         for(;;){
              byte[] packet = reader.readPacket();
         if(reset==1)
         for(i=0; i<MAX_NODES; i++)
              packetcount=0;
              PL[i]=0;
              counter[i]=0;     
              if(averageReset==1)
              secondsElapsed=0;
              avgPacketCount[i]=0;
              totalPacketsReceived[i]=0;
         reset =0;
         if(FirstRun==0)
         packetcount[packetHold]++;
         totalPacketsReceived[packetHold]++;
         PPS++;
         FirstRun=0;
         averageReset=0;
         packetcount[packet[6]]++;
         totalPacketsReceived[packet[6]]++;
         PPS++;
         strengthUnsigned = ((int)packet[8])& 0xFF;
         RSSI[packet[6]]=RSSI[packet[6]]+strengthUnsigned;
    if((packet[10]==1 && Transition==1) || (packet[10]==0 && Transition==0))
         secondsElapsed++;
         if(Transition==1)
         Transition=0;
         else
         Transition=1;
         PPS--;
         packetcount[packet[6]]--;
         totalPacketsReceived[packet[6]]--;
         packetHold=packet[6];
         reset=1;
         for(i=0; i<MAX_NODES; i++)
         newContentPane.DataTable.setValueAt("asdfsa",1,1);
              System.out.println("Packet Count for Node " + i + "is: " + packetcount[i]);
              PL[i]=8 - packetcount[i];
              System.out.println("Packet Loss for Node " + i + "is: " + PL[i]);
              avgPacketCount[i]=1.0*totalPacketsReceived[i]/secondsElapsed;
              System.out.println("Avg Packet Count for " + secondsElapsed + " seconds is: " +avgPacketCount[i]);
              if(RSSI[i]!=0)
              RSSI[i]=RSSI[i]/packetcount[i];
              RSSI[i]=3*(RSSI[i]/1024);
              RSSI[i]=(-51.3*RSSI[i])-49.2;
              System.out.println("RSSI(dBm) for node " + i + "is: " + RSSI[i]);
              System.out.println();
              packetcount[i]=0;
              RSSI[i]=0;
         System.out.println("Total Packets Recieved: " + PPS);
         PPS=0;
                   System.out.println();
                   System.out.println();
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         catch (IOException e) {
         System.err.println("Error on " + reader.getName() + ": " + e);

    The best way to update your data is using a TableModel :
    When you instantiate a JTable with an array of objects, it creates a DefaultTableModel which actualy stores your data.
    So, you should create your TableModel, and feed it with the data. Each time the data is updated, the TableModel must notify the JTable, so the new data can be shown :
    here's a simple example
    public class MyModel extends AbstractTableModel
    Object[][] data;
    //you must implement some abstract methods declared in AbstractTableModel
    //the method you use to update the data (you can give it the name you want)
    setData(Object[][] _data)
    data=_data;
    fireTableDataChanged();//method of AbstractTableModel that notifies the data has changed
    public void main(String[] s)
    MyModel tableModel = new MyModel();
    JTable table = new JTable(tableModel);
    JFrame frame = new JFrame();
    frame.getContentPane().add((new JScrollPane()).getViewport().add(table);
    frame.pack();
    frame.setVisible(true);
    tableModel.setData(new Object[][]{{"one", "two"}, {"three", "four"};
    thread.sleep(5000);
    tableModel.setData(new Object[][]{{"five", "six"}, {"seven", "eight};
    You will see the table displaying one, two, three, four, during 5 seconds, and then it will display five, six...

  • JButton event requires code to finish before updating JTable

    Hi everyone,
    I need some help with Java. I've been creating my first Java app and hit a wall where cannot find a solution on Google.
    I have a JFrame with a button called "Start".  The code behind the "Start" button triggers a function (startwork() ) that traverses through log files and then inserts rows into my JTable.  If I call the startwork() function from the Start button action performed event, then when it inserts the rows to the JTable it is not immediately shown... the code has to finish before the JTable is refreshed.  However, if I run the startwork() function as soon as the JFrame is displayed (from the main() function) then I can see the Jtable being populated dynamically as it is inserting the rows.
    Can someone explain how to allow the user to click on the START button and yet behave correctly to where the JTable is updated properly so that I can see the rows being inserted as it progresses. 
    Thank you!

    Thank you for the reply. However, I find it strange that I need to write a SwingWorker sub-class for every button in my GUI that wishes to do some meaningful work.  No other programming language that I have used does this. In Visual Basic, we simply add a function in the event handler and that is it.  It seems overkill to write a SwingWorker class to basically create another thread that runs some code. I don't see why my GUI has to completely freeze just because I run code in an event.

  • Error in updating Jtable Database

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

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

  • Error while updating JTable

    WHAT I WANT TO DO:
    I display a list of items and their characteristics in a JTable (the content is in a DefaultTableModel). Each time a user buys items, I refresh the list for all the users currently connected to the server. The client buying the item is also prompted through a JOptionPane that his order has been processed.
    THE CODE:
    controller.handleOrder();
    JOptionPane.showMessageDialog(new JFrame(), message, "SUCCESSFUL ORDER", JOptionPane.INFORMATION_MESSAGE);Another thread calls the following function, which refreshes the list in the JTable:
    public void updateFlowers(){
         // method in Controller
         setChanged();
         notifyObservers();
        |
        V
    public void update(Observable arg0, Object arg1) {
         // method in Frame
         loadFlowers();
        |
        V
    private void loadFlowers(){
         // method in Frame
         flowerTableModel = controller.loadFlowers();
         flowerTable.setModel(flowerTableModel);
       |
       V
    public DefaultTableModel loadFlowers()  {
         // method in Controller
         Object table[][]=null;
         flowers=ClientOperations.getInstance().getFlowers();
         if (flowers!=null){
              table=new Object[flowers.size()][3];
              int i=0;
              for (Flower flower:flowers){
                   table[0]=flower.getSpecies();
                   table[i][1]=new Float(flower.getPrice());
                   table[i][2]=new Integer(flower.getInStock());
                   i++;
         DefaultTableModel flowersDTM=new DefaultTableModel(table,TABLE_HEADER);
         return flowersDTM;
    THE ERROR I GET:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paintGrid(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
         at javax.swing.plaf.ComponentUI.update(Unknown Source)
         at javax.swing.JComponent.paintComponent(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintToOffscreen(Unknown Source)
         at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
         at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
         at javax.swing.RepaintManager.paint(Unknown Source)
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.Dialog$1.run(Unknown Source)
         at java.awt.Dialog$3.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.awt.Dialog.show(Unknown Source)
         at javax.swing.JOptionPane.showOptionDialog(Unknown Source)
         at javax.swing.JOptionPane.showMessageDialog(Unknown Source)
         at javax.swing.JOptionPane.showMessageDialog(Unknown Source)
         at ui.OrderFrame.handleOrder(OrderFrame.java:185)
         at ui.OrderFrame.access$1(OrderFrame.java:181)
         at ui.OrderFrame$ButtonListener.actionPerformed(OrderFrame.java:218)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    I would very much appreciate it if you could explain why I get this error and how it can be solved.
    Thank you,
    Cristina                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Updating of Swing components must be done on the EDT. Wrap the code in SwingUtilities.invokeLater() or use a SwingWorker.
    Read the section from the Swing tutorial on Concurrency for more information.

  • How to auto update JTable during runtime

    Can anyone tell me how to dynamically update a JTable during execution, what i mean isin the I want the table to automatically add new rows as i enter new data.
    if I pass the object array reference of the TableModel to a method, then add more objects to the array and the revalidate the JTable will it work, or how do I do it ? Thanks

    Your table model should extend AbstractTableModel. And when (for example) it adds a row to whatever data structure is supporting the model, it should call fireTableRowsInserted... you can find out more about those methods in the API documentation. You don't need to revalidate or invalidate or validate the JTable, at least I don't have that in my code anywhere.

Maybe you are looking for

  • ACS Local databse authentication as a failover to Active Directory

    Hi all Router- 10.10.10.1 ACS-10.10.10.2 AD-10.10.10.3 in AD - created  a group called "telnet users" - added user with name of - john I have added cisco router as clients in Cisco ACS 5.1 and integrated with Active directory. when i telnet to 10.10.

  • Why can't Nokia let us edit timezones

    Hi, I am nearly about to switch manufacturers. My N95 calendar is useless because Nokia decide to only include some offsets from GMT and some daylight savings. Australian Central Standard Time is nearly always missing. Why can't Nokia make it so end

  • Galaxy Nexus Camera not working after update to 4.1.1

    Did the OTA update when prompted.  Now getting the "Unfortunately Gallery has stopped" error message (flashes quickly). Gallery will open for viewing photos bu the camera app not functional at all. Help! Anyone?

  • White Space behind Loading Animation

    I have a DW doc, with Black background color set in page properties. I have a table with text and a sfw. When the page opens in browser, as the animation loads there is a big white hole in the swf space. I've tried blacking the table in the backgroun

  • Is there a way to copy and paste the same changes in keyframes along the timeline?

    Hi, I was doing an effect (changing the parameters in keyframe editor) and I wanted to do the same effect in specific moments on the timeline. Is it possible to copy and paste the same effect on the keyframe editor? Thanks