-1

As you see, I've been researching and tried to set a thread in main.java class. This is the main method:

public static void main(String args[]) {     
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new main().setVisible(true);
            check ch = new check();
            ch.start();          
        }
    });
}

Main method calls a thread called ch , from check.java class.

This is the thread class:

public class check extends Thread {

    public JTextArea estado = new JTextArea();   
    public JTextField updatedVersion = new JTextField();
    public JLabel updatedLabel = new JLabel();
    public String catchUpdatedVersion;
    int UPDATENUMBER;
    int CURRENTNUMBER;

    public void run() {
        String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
        String name = "thread.inf";
        File file = new File(name);
        try {
            URLConnection conn = new URL(infURL).openConnection();
            conn.connect();
            estado.append("Conectando al servidor...");
            estado.append(System.getProperty("line.separator"));
            estado.append(" -- Buscando actualizaciones... --");
            estado.append(System.getProperty("line.separator"));
            InputStream in = conn.getInputStream();
            OutputStream out = new FileOutputStream(file);
            int b = 0;
            while (b != -1) {
                b = in.read();
                if (b != -1) {
                    out.write(b);
                }
            }
            out.close();
            in.close();
        } catch (MalformedURLException ex) {
        } catch (IOException ioe) { }

        String fileToReadUpdatedVersion = "thread.inf";
        try {
            BufferedReader br = new BufferedReader(
                    new FileReader(fileToReadUpdatedVersion));
            String brr = br.readLine();
            catchUpdatedVersion = brr.substring(34,42);
            String catchUpdatedShortVersion = brr.substring(15,16);
            UPDATENUMBER = Integer.parseInt(catchUpdatedShortVersion);

            String fileToReadCurrentVer = "thread.inf";
            BufferedReader brrw = new BufferedReader(
                                new FileReader(fileToReadCurrentVer));
            String brrwREAD = brrw.readLine();
            String catchCurrentShortVersion = brrwREAD.substring(15,16);
            CURRENTNUMBER = Integer.parseInt(catchCurrentShortVersion);

            if (CURRENTNUMBER >= UPDATENUMBER) {
                estado.setText("No se han encontrado actualizaciones.");
            } else {
                updatedVersion.setForeground(new Color(0,102,0));
                updatedLabel.setForeground(new Color(0,153,51));
                updatedVersion.setText(catchUpdatedVersion);
                estado.append("-------------------" +
                        "NUEVA ACTUALIZACIÓN DISPONIBLE: " +
                            catchUpdatedVersion + " -------------------");;
                estado.append(System.getProperty("line.separator"));
                estado.append("Descargando actualizaciones... " +
                            "Espere por favor, no cierre este " +
                                "programa hasta que esté completado...");
                try {
                    String updateURL = "https://thread.googlecode.com/" +
                                                    "svn/trunk/thread.inf";
                    String updatedname = (catchUpdatedVersion + ".zip");
                    File updatedfile = new File(updatedname);
                    URLConnection conn = new URL(updateURL).openConnection();
                    conn.connect();
                    estado.append(System.getProperty("line.separator"));
                    estado.append("   Archivo actual: " + updatedname);
                    estado.append(System.getProperty("line.separator"));
                    estado.append("   Tamaño: " + 
                        conn.getContentLength() / 1000 / 1000 + " MB");
                    InputStream in = conn.getInputStream();
                    OutputStream out = new FileOutputStream(updatedfile);
                    int c = 0;
                    while (c != -1) {
                        c = in.read();
                        if (c != -1) {
                            out.write(c);
                        }
                    }
                    out.close();
                    in.close();    
                } catch (MalformedURLException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (IOException ioe) {
            System.out.println(ioe);
            ioe.printStackTrace();
        }
    }
}

When I run the program, the thread does not work fine. It is supposed to download a file and then display its progress in a JTextArea in main.java class. It does download the file, but nothing appears in JTextArea.

Where is my mistake?

EDIT: Showing all the code.

Seba Paz
  • 55
  • 3
  • 9
  • 2
    The problem is not displaying and you haven't shown the code that's supposed to be displaying... – Sotirios Delimanolis Sep 28 '13 at 18:20
  • Take care that gui works in the Event Dispatch Thread. – nachokk Sep 28 '13 at 18:23
  • @SotiriosDelimanolis ok. I put all the code – Seba Paz Sep 28 '13 at 18:24
  • 1
    You need to use SwingWorker (http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html) then use the process method to update the UI (http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html#process(java.util.List)). – Lol Sep 28 '13 at 18:32
  • 1
    Without going into detail - this code looks like a big hack. You're mixing up code that builds up your UI and behavioural/business logic code, that loads the data from the web. You're doing UI related stuff in a non-UI thread and so on. I don't know, where to start... – isnot2bad Sep 28 '13 at 18:46
  • What is your recommended way to do this ? – Seba Paz Sep 28 '13 at 19:19
  • @Lol I know swingworker is the best way, I just need to know how to integrate this giant code into a swingworker class. I will be researching, if I have any doubt I will ask a question here in SO – Seba Paz Sep 28 '13 at 19:47

1 Answers1

1

Problem #1

The components you are trying to update are not, in any way, connected to the screen...

public JTextArea estado = new JTextArea();   
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();

That means, anytime you interact with these components, it's doing nothing to what's on the screen...

Problem #2

You're trying to make modifications to the UI from outside the context of the Event Dispatching Thread. This is significant violation of the Swing threading rules.

public class Check extends SwingWorker<String, String> {

    private JTextArea estado;   
    Private JTextField updatedVersion;
    private JLabel updatedLabel;
    private String catchUpdatedVersion;
    int UPDATENUMBER;
    int CURRENTNUMBER;

    public Check(JTextArea estado, JTextField updatedVersion, JLabel updatedLabel) {
        this.estado = estado;
        this.updatedVersion = updatedVersion;
        this.updatedLabel = updatedLabel;
    }

    protected void process(List<String> values) {
        for (String value : values) {
            estado.append(value);
        }
    }

    protected String doInBackground() throws Exception {
        String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
        String name = "thread.inf";
        File file = new File(name);

        URLConnection conn = new URL(infURL).openConnection();
        conn.connect();
        publish("Conectando al servidor...");
        publish(System.getProperty("line.separator"));
        publish(" -- Buscando actualizaciones... --");
        publish(System.getProperty("line.separator"));
        /*...*/          
    }
}

IfYou need to do any post-processing, then you also override done which will be called after doInBackground has existed, but is called within the context of the EDT

For more details read through Concurrency in Swing

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Yes, I solved problem 1 and 2 by implementing a swingworker method, now everything works fine. My program is supposed to download a file and represent its percentage in a progressbar. It actually downloads the file, but the progressbar doesn't move until the download is completed, then suddenly it marks 100%. I can't see the "animation" between 0 and 100 – Seba Paz Sep 28 '13 at 22:15
  • 1
    `SwingWorker` has the capacity to provide progress feedback itself, for [example](http://stackoverflow.com/questions/16937997/java-swingworker-thread-to-update-main-gui/16938228#16938228), [example](http://stackoverflow.com/questions/15199091/progress-bar-java/15199220#15199220), [example](http://stackoverflow.com/questions/12020949/jprogressbar-isnt-progressing/12021971#12021971), – MadProgrammer Sep 28 '13 at 22:26