Link to home
Start Free TrialLog in
Avatar of Murdoc
Murdoc

asked on

Updating window with Jtable after adding of a row

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

Avatar of girionis
girionis
Flag of Greece image

AFAIK if you update the model the changes should be reflected on the table as well.
Avatar of Murdoc
Murdoc

ASKER

but how to update it??

Regards
Use the setModel() method of the JTable class and pass it the new model.
You might as well do:

table.getModel().fireTableStructureChanged();
Avatar of Murdoc

ASKER


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




can u post the complete code?
Avatar of Murdoc

ASKER

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
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();

      }
}
Avatar of Murdoc

ASKER

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
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.
Avatar of Murdoc

ASKER

...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
> table.addNotify();
> table.setModel(model);

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

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
The SwingWorker class should meet your needs
try this:

model.addRow(new Object[]{""+b,f,s,d});
model.fireTableDataChanged();
>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.
Avatar of Murdoc

ASKER

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
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
Avatar of Murdoc

ASKER

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
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.
Avatar of Murdoc

ASKER

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
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.
Avatar of Murdoc

ASKER

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
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.
Avatar of Murdoc

ASKER

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
Avatar of Murdoc

ASKER

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
Try this:

public class test extends Thread  {
 DefaultTableModel model = new DefaultTableModel();
The SwingWorker class I mentioned earlier helps making what you are trying to do a lot simpler :)
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Murdoc

ASKER

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



Avatar of Murdoc

ASKER

I got it allready

It suppose to be:  
public class test extends Thread  {

public static DefaultTableModel model = new DefaultTableModel();


Thanks for help guys

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Murdoc

ASKER

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
Actually no, I thought you didn't know you could do a split on 50 points, that's why I posted the message :)