【问题标题】:How to make the text from a JTextArea change when the text file from where it gets it's text modifies?当从其获取文本的文本文件修改时,如何使 JTextArea 中的文本发生更改?
【发布时间】:2016-03-27 16:29:43
【问题描述】:

我有一个从文本文件中获取内容的 JTextArea。每当修改文件文本时,如何修改文本区域的内容? 这是上下文中的代码:

public class AdminGui {
private JFrame frame = new JFrame();
private JPanel xPanel = new JPanel(new GridLayout(1, 3, 20, 20));
private JPanel labelPanel = new JPanel(new GridLayout(2, 1, 400, 400));
private JPanel textPanel = new JPanel(new GridLayout(2, 1, 400, 400));
private JPanel btnPanel = new JPanel(new GridLayout(4, 1, 20, 20));
private JLabel loginLabel = new JLabel();
private JLabel nameLabel = new JLabel("Item name:");
private JLabel quantityLabel = new JLabel("Quantity:");
private JTextField nameText = new JTextField();
private JTextField quantityText = new JTextField();
private JButton addItem = new JButton("Add new item");
private JButton removeItem = new JButton("Remove item");
private JButton addToStock = new JButton("Add to stock");
private JButton removeFromStock = new JButton("Remove from stock");
private JTextArea items = new JTextArea();
private JButton history = new JButton("Command history");
File file1 = new File("D:\\Documents\\JavaProj\\OrderManagement\\res\\items.txt");
Scanner fileScanner;

public AdminGui(String username) {
    try {
        fileScanner = new Scanner(file1);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.err.println(e);
    }
    while (fileScanner.hasNext()) {
        items.append(fileScanner.nextLine()+"\n");
    }
    items.setEditable(false);
    frame.setLayout(new BorderLayout());
    loginLabel.setText("You are logged in as " + username);
    loginLabel.setHorizontalAlignment(JLabel.CENTER);
    frame.add(loginLabel, BorderLayout.NORTH);
    frame.add(history, BorderLayout.SOUTH);
    labelPanel.add(nameLabel);
    labelPanel.add(quantityLabel);
    frame.add(labelPanel, BorderLayout.WEST);
    textPanel.add(nameText);
    textPanel.add(quantityText);
    btnPanel.add(addItem);
    btnPanel.add(removeItem);
    btnPanel.add(addToStock);
    btnPanel.add(removeFromStock);
    xPanel.add(textPanel);
    xPanel.add(btnPanel);
    xPanel.add(items);
    frame.add(xPanel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
}

因此,每当 items.txt 文件发生更改时,我都希望 items textArea 相应地更改。

【问题讨论】:

  • 您可以存储文件的最后修改日期,如果修改日期发生变化,则可以获取文件内容。

标签: java swing file-io


【解决方案1】:

Java 确实提供了WatchService,它可用于在文件被修改、删除、在目录中创建时拦截事件。这是一个演示功能的简单类,您可以根据需要进行修改。

    import java.nio.file.*;
    import static java.nio.file.StandardWatchEventKinds.*;
    import java.io.*;

    public class FileWatcher {

        private final WatchService watcher;
        private final Path dir;

        /**
         * Creates a FileWatcher and registers the given directory to be watched
         */
        FileWatcher(Path dir) throws IOException {
            this.watcher = FileSystems.getDefault().newWatchService();
            dir.register(watcher, ENTRY_MODIFY);
            dir.register(watcher, ENTRY_CREATE);
            dir.register(watcher, ENTRY_DELETE);
            System.out.printf("Watching the directory...%s%n", dir);
            this.dir = dir;
        }

        /**
         * Process all events for the key queued to the watcher
         */
        public void processEvents() {
            while(true) {

                // wait for key to be signaled
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException x) {
                    return;
                }

                for (WatchEvent<?> event: key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();

                    if (kind == OVERFLOW) {
                        continue;
                    }

                    //The filename is the context of the event.
                    WatchEvent<Path> ev = (WatchEvent<Path>)event;
                    Path filename = ev.context();

                    System.out.format("The file %s has been %s%n", filename, kind);
                    //more processing here...
                }

                //Reset the key -- this step is critical if you want to receive
                //further watch events. If the key is no longer valid, the directory
                //is inaccessible so exit the loop.
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        }


        public static void main(String[] args) throws IOException {
            //register directory and process its events
            Path dir = Paths.get(args[0]);
            new FileWatcher(dir).processEvents();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多