用户停止在Java TextArea中键入内容时如何在另一个线程中保存和拼写检查

我创建了一个简单的文本编辑器,该编辑器每分钟自动保存txt文件,还使用languagetool java api拼写检查TextArea。我想在用户停止键入时完成自动保存,并且在用户停止键入时也完成拼写检查。我想我可以使用与textarea关联的OnKeypressed和OnKeyRealesed方法以某种方式做到这一点,并使用System.currentTimeMillis方法,但是我无法弄清楚。我还认为最好在另一个线程中进行这些处理,但是我不确定如何实现。

自动保存和拼写检查是通过使用TimerTask的AutoSave和AutoSaveMac类创建的,然后每分钟运行一次。这些类可在应用初始化时运行的runAutoSave()函数中使用。

所以我想我的问题是,当用户停止键入时,如何在另一个线程中运行保存和拼写检查?

请让我知道我是否还能回答任何其他问题。

编辑:我从此开始测试,删除/注释掉languagetool api的代码行。 (在FXMLController.java和pom.xml中)由于languagetool api在运行时需要一点点加载,因此可以更快地进行测试。我想知道当用户停止键入时是否可以保存工作,那么我将能够轻松添加languagetool api代码。

FXMLController.java

package com.mycompany.maveneditormre;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javax.swing.JFileChooser;
//import org.languagetool.JLanguageTool;
//import org.languagetool.language.BritishEnglish;
//import org.languagetool.rules.RuleMatch;

public class FXMLController implements Initializable {
    String opSystem = new String();
    String documentsPath = new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
    @FXML public TextArea textArea;
    @FXML public TextArea spellcheckTextArea;
    @FXML public TextField textFieldFileFolderName;
    private final TextArea textArea2 = new TextArea();
    public static volatile int keyPressTime = 00;
    public static volatile int keyReleaseTime = 00;
//    JLanguageTool langTool = new JLanguageTool(new BritishEnglish());
    
    
    public class FirstThread implements Runnable {
        
        public FirstThread(){
        
        }
    
        public void run(){
        
        System.out.println("MyThread running");
       
       
        }
    
    }
    
    @FXML
    private void handleKeypressed() throws IOException {
        keyPressTime = (int) System.currentTimeMillis();
        
    }
    
    @FXML
    private void handleKeyReleased() throws IOException{
        keyReleaseTime = (int) System.currentTimeMillis();
          
    }
    
    private void Save(String content,File file){
        try {
            FileWriter fileWriter;
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(FXMLController.class
                .getName()).log(Level.SEVERE,null,ex);
        }
    }
    
    private void runAutoSave(){
        if (this.opSystem.contains("mac")){
                Timer timer = new Timer();
                TimerTask task = new AutoSaveMac();
                timer.schedule(task,2000,60000);
            } else {
                Timer timer = new Timer();
                TimerTask task = new AutoSave();
                timer.schedule(task,60000);
            }
    
    
    }
    
    class AutoSave extends TimerTask {
      
        @Override
        public void run() {
             
            if(textArea2.getText().equals(textArea.getText())){
                // do nothing
            } else {
                // autosave new folder and file if needed
//                String[] firstLineOfTextArea = textArea.getText().split("\\n");
                    String[] firstLineOfTextArea = textFieldFileFolderName.getText().split("\\n");
                    String[] folderAndFileName = firstLineOfTextArea[0].split("-",2);
                    Path path = Paths.get(documentsPath + "\\ssef\\" + folderAndFileName[0]);
                if (Files.exists(path)) {
                    // Do nothing
                } else {
                    new File(documentsPath + "\\ssef\\" + folderAndFileName[0]).mkdir();
                }
                File file = new File(String.format(documentsPath + "\\ssef\\" + folderAndFileName[0]+ "\\%s.txt",folderAndFileName[1] ));
                Save(textArea.getText().replaceAll("\n",System.getProperty("line.separator")),file);
                textArea2.setText(textArea.getText());
                
//                spell check
//                List<RuleMatch> matches = null;
//                        try {
//                            matches = langTool.check(textArea.getText());
//                            System.out.println(matches);
//                        } catch (IOException ex) {
//                            Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE,ex);
//                        }
//                        
//                        if (matches.isEmpty() == true) { 
//                            spellcheckTextArea.clear();
//                        }
//                            
//                            for (RuleMatch match : matches) {
//                            spellcheckTextArea.setText(spellcheckTextArea.getText() + "\n" + "Potential error at characters " + match.getFromPos() + "-" + match.getToPos() + ": " + match.getMessage() + "\n" + "Suggested correction(s): " + match.getSuggestedReplacements());
//
//                            System.out.println("Potential error at characters " + match.getFromPos() + "-" + match.getToPos() + ": " + match.getMessage());
//                            System.out.println("Suggested correction(s): " + match.getSuggestedReplacements());
//                            }
                        
                    
            
            }
        } 
    }
    
    class AutoSaveMac extends TimerTask {
      
        @Override
        public void run() {
             
            if(textArea2.getText().equals(textArea.getText())){
                // do nothing
            } else {
                // autosave new folder and file if needed
                String[] firstLineOfTextArea = textFieldFileFolderName.getText().split(System.getProperty("line.separator"));
                System.out.println(firstLineOfTextArea[0] + " first line of textarea");
                String[] folderAndFileName = firstLineOfTextArea[0].split("-",2);
                Path path = Paths.get(documentsPath + "/Documents" + "/ssef/" + folderAndFileName[0]);
                
                if (Files.exists(path)) {
                    // Do nothing
                } else {
                    new File(documentsPath +  "/Documents" + "/ssef/" + folderAndFileName[0]).mkdir();
                }
                File file = new File(documentsPath + "/Documents" + "/ssef/" + folderAndFileName[0] + "/" + folderAndFileName[1]+ ".txt" );
                Save(textArea.getText().replaceAll("/n",file);
                textArea2.setText(textArea.getText());
                
//                List<RuleMatch> matches = null;
//                        try {
//                            matches = langTool.check(textArea.getText());
//                            System.out.println(matches);
//                        } catch (IOException ex) {
//                            Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE,ex);
//                        }
//                        
//                        if (matches.isEmpty() == true) { 
//                            spellcheckTextArea.clear();
//                        }
//                            
//                            for (RuleMatch match : matches) {
//                            spellcheckTextArea.setText(spellcheckTextArea.getText() + "\n" + "Potential error at characters " + match.getFromPos() + "-" + match.getToPos() + ": " + match.getMessage() + "\n" + "Suggested correction(s): " + match.getSuggestedReplacements());
//
//                            System.out.println("Potential error at characters " + match.getFromPos() + "-" + match.getToPos() + ": " + match.getMessage());
//                            System.out.println("Suggested correction(s): " + match.getSuggestedReplacements());
//                            }
            
            }
        } 
    } 
    
    private void createOpeningFolder(){
        
        if (opSystem.contains("mac")) {
            Path path = Paths.get(documentsPath + "/Documents" + "/ssef");
            if (Files.exists(path)) {
                    // Do nothing
            } else {
            new File(documentsPath + "/Documents" + "/ssef").mkdir();
            }
        
        } else {
            Path path = Paths.get(documentsPath + "\\ssef");
            if (Files.exists(path)) {
                    // Do nothing
            } else {
            new File(documentsPath + "\\ssef").mkdir();
            }
        }
        
    }
    
    @Override
    public void initialize(URL url,ResourceBundle rb) {
        // TODO
        String osname = System.getProperty("os.name").toLowerCase();
        this.opSystem = osname;
        System.out.println("Operating System: "   + this.opSystem);
        textFieldFileFolderName.setfocusTraversable(true);
        textArea.setwraptext(true);
        Runnable firstThread = new FirstThread();
        new Thread(firstThread).start();
        createOpeningFolder();
        runAutoSave();
    }    
}



scene.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<BorderPane fx:id="borderPaneRoot" prefHeight="600.0" prefWidth="1000.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.mycompany.maveneditormre.FXMLController">

    <center>
    <GridPane>
      <children>
        <TextField fx:id="textFieldFileFolderName" prefWidth="200.0" promptText="foldername-filename" GridPane.columnIndex="0" GridPane.rowIndex="0"    />
        <TextArea fx:id="textArea" prefWidth="200.0" promptText="note taking" wraptext="true" GridPane.columnIndex="0" GridPane.rowIndex="1" onKeypressed="#handleKeypressed" onKeyReleased="#handleKeyReleased" />
      </children>
      <columnConstraints>
        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
      </columnConstraints>
      <rowConstraints>
        <RowConstraints maxHeight="202.0" minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        <RowConstraints maxHeight="376.0" minHeight="10.0" prefHeight="376.0" vgrow="SOMETIMES" />
      </rowConstraints>
    </GridPane>
  </center>
  
  <bottom>
    <TextArea fx:id="spellcheckTextArea" editable="false" promptText="spellchecking" wraptext="true" />
  </bottom>
  
</BorderPane>

确保将以下内容添加到pom.xml

<dependencies>
        <dependency>
            <groupId>org.languagetool</groupId>
            <artifactId>language-en</artifactId>
            <version>4.8</version>
        </dependency>
    </dependencies>
Ian701 回答:用户停止在Java TextArea中键入内容时如何在另一个线程中保存和拼写检查

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1327733.html

大家都在问