简体   繁体   中英

printing text file using java swing

i created two classes the first reads from a file and the seconde is supposed to prints the file using java swing but the only thing that it shows is null ive tried to use String.valueOf(word) to cast word to string but that doesnt work either

private static String getFileInfo(){    

    File listOfWords = new File("words.txt");

    try {
        BufferedReader getInfo = new BufferedReader(new FileReader(listOfWords));
        String word = getInfo.readLine();
        while(word!=null) {
            System.out.println(word);
            word = getInfo.readLine();
        }
    }
    catch(FileNotFoundException e) {
       System.exit(0);
    }
    catch(IOException e){   
        System.exit(0);
    }
    return word;
}

public LabelThread() {
    try {
        JFrame frame  = new JFrame("Label");
        frame.setSize(500, 500);

        textLabel = new JLabel(String.valueOf(word));
        frame.setContentPane(textLabel);

        frame.setVisible(true);

        MyThread thread = new MyThread();
        MyThread.sleep(15000); // 15 secondes then 10 then 5
        thread.start();  

    } catch (InterruptedException ex) {

    }
}
class MyThread extends Thread{


    public void run() {
        System.out.print("Running thread");
        textLabel.setText("");
    }

You can only change things like label text when changes to Swing JComponents are scheduled to run on the Event Dispatch Thread. https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

In order to do this, try this:

class MyRunnable implements Runnable{
    public void run() {
        System.out.print("Running thread");
        textLabel.setText("");
    }
}

And then...

Runnable my Runnable = new MyRunnable(....);
javax.swing.SwingUtilities.invokeLater(myRunnable);

That should set the label text as you are hoping to achieve. It's a good idea to schedule all painting of swing components like that.

You should never use the EDT for long running operations: only GUI painting. If you have a task that does a mixture of I/O and GUI painting you need to use SwingWorker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM