【问题标题】:printing text file using java swing使用java swing打印文本文件
【发布时间】:2018-03-13 17:08:44
【问题描述】:

我创建了两个类,第一个类从文件中读取,第二个类应该使用 java swing 打印文件,但它唯一显示的是 null 我试图使用 String.valueOf(word) 将单词转换为字符串,但是这也不起作用

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

【问题讨论】:

  • words.txt 必须在项目的根目录中才能使用此声明,否则您需要完整的限定路径名
  • 您正在阅读getFileInfo 中的文件,但我没有看到您在任何地方调用该方法。此外,wordgetFileInfo 中的局部变量,但您将其称为类级别变量。这甚至为你编译吗?最后,您正在尝试将word 写入标准输出,是用于调试还是您希望这样做?我的建议是从LabelThread 构造函数调用getFileInfo,并将该返回值分配给textLabel。您还需要连接从文件中读取的字符串。

标签: java swing file user-interface text


【解决方案1】:

仅当对 Swing JComponents 的更改计划在事件调度线程上运行时,您才能更改标签文本之类的内容。 https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

为了做到这一点,试试这个:

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

然后……

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

这应该设置您希望实现的标签文本。像这样安排所有秋千组件的绘制是个好主意。

您不应该将 EDT 用于长时间运行的操作:仅用于 GUI 绘制。如果您有一个混合了 I/O 和 GUI 绘制的任务,您需要使用SwingWorker

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多