为什么我的 JTextArea 追加不起作用



今天,我想拿起java,通过制作一些东西来列出目录中的所有文件(这样我就可以很容易地看到我在数字卡集合中错过了哪些卡(。
我让文件步行器工作,但是,它不会将文件名附加到我制作的 JTextArea 中。

我有这个代码:

package finlaydag33k.swing.gui;
import java.awt.EventQueue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
public class Gui extends JFrame {
    private JPanel contentPane;
    static JTextArea filePanel = new JTextArea();
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Gui frame = new Gui();
                    frame.setVisible(true);
                    try(Stream<Path> paths = Files.walk(Paths.get("/home/finlay/Pictures"))) {
                        paths.forEach(filePath -> {
                            if (Files.isRegularFile(filePath)) {
                                //System.out.println(filePath);
                            filePanel.append("Hii");
                            }
                        });
                    }
                    System.out.println(System.currentTimeMillis() - System.currentTimeMillis());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public Gui() {
        setAlwaysOnTop(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new MigLayout("", "[][grow]", "[][grow]"));
        JTextArea filePanel =  new JTextArea();
        contentPane.add(filePanel, "cell 1 1,grow");
    }
}

line 34,问题似乎发生了(我只是将hii添加为占位符,以便找出问题(。
我没有收到任何错误(只有一些警告说 The serializable class Gui does not declare a static final serialVersionUID field of type long,但这不应该导致它吗?
GUI 只是加载文本区域为空。我希望有人能够帮助我:)

请原谅我在阅读代码时可能会遇到的任何畏缩:)
干杯!

您有两个名称相同但作用域不同的实例:

public class Gui extends JFrame {
    static JTextArea filePanel = new JTextArea();

在构造函数中:

public Gui() {
    ...
    JTextArea filePanel =  new JTextArea();

这意味着您将构造函数中声明的那个添加到框架中,但在 main 中附加静态的。根本不是同一个实例。

删除静态(因为这没有意义(

public class Gui extends JFrame {
     JTextArea filePanel;

删除第二个声明,以启动构造函数中的变量

public Gui() {
        ...
        filePanel =  new JTextArea();

并使用 main 中的变量实例来访问它

frane.filePanel.append("Hii");

有关更多说明,请搜索有关 Java 中的阴影字段的信息。这就是你正在做的事情。您可以通过在不同的作用域中声明相同的变量来隐藏变量。

最新更新