Solved

Updating window with Jtable after adding of a row

Posted on 2004-08-11
36
1,071 Views
Last Modified: 2013-11-23
Hi

I got some problem with updating window while adding another rows to Jtable.
Here is my code.


 import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;


public class AddRow extends JFrame
{
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
   
     public AddRow()
     {      
         model.addColumn("L.p.:");
         model.addColumn("From:");
         model.addColumn("Subject:");
         model.addColumn("Date:");
         
         getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
         JButton add = new JButton("Connect");
         JButton exit = new JButton("Exit");
         JPanel panel=new JPanel();
         panel.add(exit);
         panel.add(add);
         getContentPane().add(panel,BorderLayout.SOUTH);
(....)

for (int b=1;b<=ile;b++)
{
p1.println("RETR "+Integer.toString(b));
recvreply=d1.readLine();
if (!recvreply.startsWith("-ERR"))
{
while(!recvreply.startsWith("."))
{
   if (recvreply.startsWith("From:") ||recvreply.startsWith("FROM:")  )
   {
   f=recvreply.substring(5,recvreply.length());
   }
   
     if (recvreply.startsWith("Subject:")||recvreply.startsWith("SUBJECT:"))
   {
    s=recvreply.substring(8,recvreply.length());
   }
     
     if (recvreply.startsWith("Date:") ||recvreply.startsWith("DATE:")  )
   {
       d=recvreply.substring(5,recvreply.length());
   }
   
        if (recvreply.startsWith("Return-Path:"))
   {
   }
recvreply=d1.readLine();
}
model.addRow(new Object[]{""+b,f,s,d});


*****************************************   need to update here window with Jtable and have no idea how to achieve this 'cause just learning java  :):):)



}    
}    
s1.close();

} catch(IOException e)
{
System.out.println("Error in Connecting to Port");
}


    }
   
    public static void main(String[] args)
    {
         new AddRow().show();
         
    }
}


Thanks for help.


Regards

0
Comment
Question by:Murdoc
  • 14
  • 12
  • 5
  • +2
36 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 11772221
AFAIK if you update the model the changes should be reflected on the table as well.
0
 

Author Comment

by:Murdoc
ID: 11772312
but how to update it??

Regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 11772395
Use the setModel() method of the JTable class and pass it the new model.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11772407
You might as well do:

table.getModel().fireTableStructureChanged();
0
 

Author Comment

by:Murdoc
ID: 11774712

table.getModel().fireTableStructureChanged(); --->> it doesen't work cause there is no such metod
and first clue " table.setModel(model);" doesen't solve the problem 'cause  window with Jtable freezes.

Regards




0
 
LVL 1

Expert Comment

by:schmida
ID: 11776750
can u post the complete code?
0
 

Author Comment

by:Murdoc
ID: 11777040
Hi.

This is my full source code:

<------------------------------------------------------------------------------------->
 import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;


public class AddRow extends JFrame
{
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
   
   
     public AddRow()
     {      
         model.addColumn("L.p.:");
         model.addColumn("From:");
         model.addColumn("Subject:");
         model.addColumn("Date:");
         table.setModel(model);
         getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
         JButton add = new JButton("Sprawd&#378;");
         JButton exit = new JButton("Exit");
         JPanel panel=new JPanel();
         panel.add(exit);
         panel.add(add);
         getContentPane().add(panel,BorderLayout.SOUTH);

         add.addActionListener(new ActionListener()
         {
              public void actionPerformed(ActionEvent event)
              {
                   addRow();
              }
         });
                  exit.addActionListener(new ActionListener()
         {
              public void actionPerformed(ActionEvent event)
              {
              System.exit(1);    
              }
         });
         
         table.setAutoResizeMode(table.AUTO_RESIZE_ALL_COLUMNS);
         setSize(200, 200);
     }
     
     private void addRow()
     {
Socket s1;
PrintStream p1;
DataInputStream d1;
String recvreply;
String f,s,d;
f= new String();
s= new String();
d= new String();

try
{
s1=new Socket("pop3.server",110);
d1=new DataInputStream(new BufferedInputStream(s1.getInputStream(),2500));
p1=new PrintStream(new BufferedOutputStream(s1.getOutputStream(),2500),true);
recvreply=d1.readLine();

p1.println("USER someuser");
recvreply=d1.readLine();


p1.println("PASS somepassword");
recvreply=d1.readLine();


p1.println("STAT");
recvreply=d1.readLine();



String wynik;
wynik="";
boolean pocz,kon;
pocz=false;
int licz=0;
int dupa=0;
for(int l=0;l<recvreply.length()-1;l++)
      {
                       if ((pocz==true)||(licz>1))
                                {
                                if ((dupa<2))
                                    {
                                    char c=recvreply.charAt(l);
                                    if (c!=' ')
                                        {
                                        wynik=wynik+recvreply.charAt(l);
                                        }
                                    }
                                }
                       
         if (recvreply.charAt(l) == ' ')
            {
            pocz=true;
            licz=licz+1;
            dupa=dupa+1;
            }
 }
int ile=Integer.valueOf(wynik).intValue();


for (int b=1;b<=ile;b++)
{
System.out.println("    ");

p1.println("RETR "+Integer.toString(b));
recvreply=d1.readLine();
if (!recvreply.startsWith("-ERR"))
{
while(!recvreply.startsWith("."))
{
   if (recvreply.startsWith("From:") ||recvreply.startsWith("FROM:")  )
   {


   f=recvreply.substring(5,recvreply.length());


   
   }
   
     if (recvreply.startsWith("Subject:")||recvreply.startsWith("SUBJECT:"))
   {

    s=recvreply.substring(8,recvreply.length());

   }
     
     if (recvreply.startsWith("Date:") ||recvreply.startsWith("DATE:")  )
   {

       d=recvreply.substring(5,recvreply.length());

   }
   
        if (recvreply.startsWith("Return-Path:"))
   {
   //System.out.println(recvreply);    
   }




recvreply=d1.readLine();

}

model.addRow(new Object[]{""+b,f,s,d});
table.addNotify();

table.setModel(model);

}    
}    
s1.close();


} catch(IOException e)
{
System.out.println("Error in Connecting to Port");
}




    // model.insertRow(0, new Object[]{f,s,d});
    }
   
    public static void main(String[] args)
    {
         new AddRow().show();
         
    }
}
<------------------------------------------------------------------------------------------->


Regards
0
 
LVL 1

Expert Comment

by:schmida
ID: 11777438
For me this works:

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class AddRow extends JFrame
{
      DefaultTableModel model;
      JTable table;

      public AddRow()
      {
            model =
                  new DefaultTableModel(
                        new Object[] { "L.p.:", "From:", "Subject:", "Date:" },
                        0);
            table = new JTable(model);

            getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
            JButton add = new JButton("Sprawd&#378;");
            JButton exit = new JButton("Exit");
            JPanel panel = new JPanel();
            panel.add(exit);
            panel.add(add);
            getContentPane().add(panel, BorderLayout.SOUTH);

            add.addActionListener(new ActionListener()
            {
                  public void actionPerformed(ActionEvent event)
                  {
                        addRow();
                  }
            });
            exit.addActionListener(new ActionListener()
            {
                  public void actionPerformed(ActionEvent event)
                  {
                        System.exit(1);
                  }
            });

            table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            setSize(200, 200);
      }

      private void addRow()
      {
            Socket s1;
            PrintStream p1;
            DataInputStream d1;
            String recvreply;
            String f, s, d;
            f = new String();
            s = new String();
            d = new String();

            try
            {
                  s1 = new Socket("pop3.server", 110);
                  d1 =
                        new DataInputStream(
                              new BufferedInputStream(s1.getInputStream(), 2500));
                  p1 =
                        new PrintStream(
                              new BufferedOutputStream(s1.getOutputStream(), 2500),
                              true);
                  recvreply = d1.readLine();

                  p1.println("USER someuser");
                  recvreply = d1.readLine();

                  p1.println("PASS somepassword");
                  recvreply = d1.readLine();

                  p1.println("STAT");
                  recvreply = d1.readLine();

                  String wynik;
                  wynik = "";
                  boolean pocz, kon;
                  pocz = false;
                  int licz = 0;
                  int dupa = 0;
                  for (int l = 0; l < recvreply.length() - 1; l++)
                  {
                        if ((pocz == true) || (licz > 1))
                        {
                              if ((dupa < 2))
                              {
                                    char c = recvreply.charAt(l);
                                    if (c != ' ')
                                    {
                                          wynik = wynik + recvreply.charAt(l);
                                    }
                              }
                        }

                        if (recvreply.charAt(l) == ' ')
                        {
                              pocz = true;
                              licz = licz + 1;
                              dupa = dupa + 1;
                        }
                  }
                  int ile = Integer.valueOf(wynik).intValue();

                  for (int b = 1; b <= ile; b++)
                  {
                        System.out.println("    ");

                        p1.println("RETR " + Integer.toString(b));
                        recvreply = d1.readLine();
                        if (!recvreply.startsWith("-ERR"))
                        {
                              while (!recvreply.startsWith("."))
                              {
                                    if (recvreply.startsWith("From:")
                                          || recvreply.startsWith("FROM:"))
                                    {

                                          f = recvreply.substring(5, recvreply.length());

                                    }

                                    if (recvreply.startsWith("Subject:")
                                          || recvreply.startsWith("SUBJECT:"))
                                    {

                                          s = recvreply.substring(8, recvreply.length());

                                    }

                                    if (recvreply.startsWith("Date:")
                                          || recvreply.startsWith("DATE:"))
                                    {

                                          d = recvreply.substring(5, recvreply.length());

                                    }

                                    if (recvreply.startsWith("Return-Path:"))
                                    {
                                          //System.out.println(recvreply);    
                                    }

                                    recvreply = d1.readLine();

                              }

                              model.addRow(new Object[] { "" + b, f, s, d });
                        }
                  }
                  s1.close();

            }
            catch (IOException e)
            {
                  System.out.println("Error in Connecting to Port");
            }

            // model.insertRow(0, new Object[]{f,s,d});
      }

      public static void main(String[] args)
      {
            new AddRow().show();

      }
}
0
 

Author Comment

by:Murdoc
ID: 11777972
You're right schmida, it works but it displays all messages when all of them are allready downloaded.I want it to be displayed in JTable message by message because I'd like to add Progressbar.
Another words I want JTable to receive first e-mail  then display this message,  next  receive  second messsage and display in JTable and so on.
Now it works fine (almost) but it display all messages  only when all of them are allready downloaded (window freezes and no message is visible until all of them will be downloaded). I'm trying to display every message in JTable message by message.


Regards
0
 
LVL 1

Expert Comment

by:schmida
ID: 11778434
Ah ok now I get your problem. Hmm maybe try to add

repaint();

or

Thread.sleep(100);

after

model.add ...

Maybe that helps. If not I suppose to implement a different thread that fetches the messages and informs the frame (use the listener pattern) whenever a new message arrived. If you do so be careful because Swing and Threads have to be handled carefully.
0
 

Author Comment

by:Murdoc
ID: 11778848
...Well...it doesn't work either...I think that clue is in  " new AddRow().show();"  but have no idea how to change  source code .

Anyway thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 11779207
> table.addNotify();
> table.setModel(model);

You don't need those two lines, addRow() is sufficient.

0
 
LVL 1

Expert Comment

by:schmida
ID: 11779579
Murdoc you didn t understand me, the problem is not that you use wrong code to add something to the table, like objects said addRow() is sufficient. The problem is that the Frame doesn t repaint while your application is busy. You have to use a second thread in order to achieve your goal. Look here there is someone with the same problem and a solution:


http://forum.java.sun.com/thread.jsp?thread=510849&forum=57&message=2427496
0
 
LVL 92

Expert Comment

by:objects
ID: 11779748
The SwingWorker class should meet your needs
0
 
LVL 1

Expert Comment

by:johnchan2000
ID: 11780551
try this:

model.addRow(new Object[]{""+b,f,s,d});
model.fireTableDataChanged();
0
 
LVL 35

Expert Comment

by:girionis
ID: 11780980
>table.getModel().fireTableStructureChanged(); --->> it doesen't work cause there is no such metod

Yes it should be fireTableChanged() or one of the related firexxx methods. It's hard to remember all methods by heart.
0
 

Author Comment

by:Murdoc
ID: 11781152
Schmida--->>I'm  trying to avoid thread's at the moment in my application 'cause I'm beginner with java, that's why I'm lookin for easier solution:)))

Johncan & girionis----->>>  I'm using sdk not enterprise edition and when I'm starting netbeans 3.6  
and typing "table.getModel().fireTableStructureChanged();"  it shows me an error and more over there is no any other method that starts with "table.getModel().fire****".


objects---->>> could  tell me a bit about SwingWorker as simple as possible :))

Thanks for help


Regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 11781194
There should be some firexxx methods in your table model.

The SwingWorker is essentially a thread. If you need to do a repaint over a component you have to use a thread, otherwise the display won't update properly.

Look here for the SwingWorker: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Murdoc
ID: 11781703
Hi again

Reasumming what you all are trying to explain me I realised that i have to learn threads in java.
:+((((    

The only problem is that i have no idea how  whom should i grant the points.

btw---->> I have found something interesting about "table.getModel().fireTableStructureChanged();"  and it means that this metod isn't required.

http://forum.java.sun.com/thread.jsp?forum=57&thread=418866
0
 
LVL 35

Expert Comment

by:girionis
ID: 11781735
The link you posted states what I already said in my very first comment:

> AFAIK if you update the model the changes should be reflected on the table as well.

As for the points, you can split them between the participants (minimum of 20 points), so in your case (50 points) you can only split them between two participants.
0
 

Author Comment

by:Murdoc
ID: 11781780
Girionis--->>  if you  would give me some simpliest example how to change my source code to use thread I will give you the points because now i'm looking in internet for some example and it makes me mad because all of them are  a bit  too complicated for me  as a beginer.

Regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 11781881
I think that the link schmida posted should give you some clues, but the general idea is:

new Thread(new Runnable(){
   public void run()
   {
      while (more data from the server)
      {
       //read row from the server
       // update table
       // repaint
      }
   }
}).start();

I would put in the run method most of the code you have in your addRow() method.
0
 

Author Comment

by:Murdoc
ID: 11781949
I got something like this below::


 import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;






public class test extends Thread  {
      public void run() {
      System.out.println("dupa");
      model.addRow(new Object[]{"test","f","s","d"});
        }

    public static void main(String[] args) {

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
        JFrame w = new JFrame("MailMan");
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = w.getContentPane();

      model.addColumn("L.p.:");
         model.addColumn("From:");
         model.addColumn("Subject:");
         model.addColumn("Date:");
         table.setModel(model);
         content.add(new JScrollPane(table), BorderLayout.CENTER);
         JButton add = new JButton("Sprawd&#378;");
         JButton exit = new JButton("Exit");
         JPanel panel=new JPanel();
         panel.add(exit);
         panel.add(add);
         content.add(panel,BorderLayout.SOUTH);


         add.addActionListener(new ActionListener()
         {
              public void actionPerformed(ActionEvent event)
              {
                  // addRow();
                Thread thread = new test();
                thread.start();

            
              }
         });
                  exit.addActionListener(new ActionListener()
         {
              public void actionPerformed(ActionEvent event)
              {
              System.exit(1);    
              }
         });



w.pack();
w.setVisible(true);


}
}




but.....in thread is an error. It shows that :


D:\MYJAR\WATKI>javac test.java
test.java:16: cannot resolve symbol
symbol  : variable model
location: class test
        model.addRow(new Object[]{"dupa","f","s","d"});
        ^
1 error



If you help me with this problem I would be very appreciate.

I will grant points to girionis  but will wait some time so maybe you can help me with code above.

Regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 11781978
Your "model" should be an instance variable and be visible to all methods within your class. Declare it outisde the main method.

BTW I still believe that points should be awarded to all people who helped you as my comments are not the only valid ones.
0
 

Author Comment

by:Murdoc
ID: 11781998
For me  it  is not a problem..

We can do  as follows : I will wait for example one week so my available points increase a bit  and then I will split points so every1 will get a bit more then i can grant now.

Regards
0
 

Author Comment

by:Murdoc
ID: 11782008
btw.  Because i'm starting with Java I have to ask a dumb question.

Where should I declare "model" in source code so??

In delphi I would know where to declare  but here  in java ...........................................


Regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 11782021
Try this:

public class test extends Thread  {
 DefaultTableModel model = new DefaultTableModel();
0
 
LVL 92

Expert Comment

by:objects
ID: 11782037
The SwingWorker class I mentioned earlier helps making what you are trying to do a lot simpler :)
0
 
LVL 92

Assisted Solution

by:objects
objects earned 25 total points
ID: 11782041
0
 

Author Comment

by:Murdoc
ID: 11782101
Thanks for your help. Objects I have to learn java more and more so i think that i have to do this thread alone .:):)
girionis--->>when i declare only  "model"  in  
public class test extends Thread  {
 DefaultTableModel model = new DefaultTableModel();

as you mentioned  makes application to crash but i think that i will try to solve this problem somehow.

In  about a week I will close this question and grant points to  girionis and objects.


Regards



0
 

Author Comment

by:Murdoc
ID: 11782154
I got it allready

It suppose to be:  
public class test extends Thread  {

public static DefaultTableModel model = new DefaultTableModel();


Thanks for help guys

0
 
LVL 35

Accepted Solution

by:
girionis earned 25 total points
ID: 11782230
Glad problem is solved :).

If you would like to split the points between only two people you have enough (25 each).
0
 

Author Comment

by:Murdoc
ID: 11782248
Hi.

My program works now perfectly  :))

If you want to split this points now ...no problem...just wanted to give you more points. But there is no need to talk, just to split the points so i'm splitting points now.

Regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 11782280
Actually no, I thought you didn't know you could do a split on 50 points, that's why I posted the message :)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11782282
:)
0
 
LVL 92

Expert Comment

by:objects
ID: 11788976
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now