简体   繁体   English

文本编辑器Java Swing actionListener保存文件

[英]Text Editor java Swing actionListener save file

Problem I am making a text editor in java using Swing. 问题我正在使用Swing在Java中创建文本编辑器。 I have a button which saves the file, using this method: 我有一个使用此方法保存文件的按钮:

private void save() {
        if (savedAs) {
            try {
                PrintWriter fout = new PrintWriter(savedAsFile);
                fout.print(textArea.getText());
                fout.close();
                this.setTitle("Text Editor - " + fileName);
                saved = true;
            } catch (FileNotFoundException ex) {
                Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

The savedAs boolean is true only when a file is first created, otherwise it just saves it without opening the save as file chooser. 仅当首次创建文件时, savedAs布尔值才为true;否则,它仅保存文件而不打开另存为文件选择器。 When I use the button everything works, however when I call the save() method from the key bindings it saves but due to this method: 当我使用按钮时,一切正常,但是当我从键绑定中调用save()方法时,它会保存,但是由于此方法:

private void textAreaKeyTyped(java.awt.event.KeyEvent evt) {                                  
    this.setTitle("Text Editor - *" + fileName);
    saved = false;
}         

It adds the asterisk back on to the title. 它将星号重新添加到标题上。 I want it to display it without the asterisk because it has been saved. 我希望它显示时不带星号,因为它已保存。 How can I make sure that the textAreaKeyTyped method does not pick up input while the action listener is calling the save method. 当动作监听器调用save方法时,如何确保textAreaKeyTyped方法不会拾取输入。

Key bindings actionlistener: 按键绑定动作侦听器:

public void initBindings() {
    textArea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(
            KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_DOWN_MASK), "actionMapKey");
    textArea.getActionMap().put("actionMapKey", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            save();
        }
    });
}

Cause I think that the text area picks up input caused by the user typing CTRL + S, therefore puts the asterisk in the title. 因为我认为文本区域会拾取由用户键入CTRL + S引起的输入,因此将星号放在标题中。

Thanks! 谢谢!

I think you have two choices: 我认为您有两种选择:

  1. Disregard the (Ctrl+s) key evt in your textAreaKeyTyped method. 忽略textAreaKeyTyped方法中的(Ctrl + s)键evt。 Maybe also disregard other key combinations that don't necessarily edit the text 也许也忽略了不必编辑文本的其他组合键

  2. Or set the title (without the asterisk) after you have saved 或在保存后设置标题(不带星号)

The most robust way would be to keep a String lastSaved object. 最健壮的方法是保留String lastSaved对象。

When you do save() do: 当您执行save()时,请执行以下操作:

lastSaved = textArea.getText();

Then in your textAreaKeyTyped() do: 然后在您的textAreaKeyTyped()执行以下操作:

boolean unchanged = textArea.getText.equals(lastSaved);

if (!unchanged) {
   // add *, enable save, etc
} else {
   // remove *, disable save, etc
}

This will have the added benefit that if a user reverses their changes their document will go back to a "not modified" state. 这将带来额外的好处,即如果用户撤消其更改,其文档将返回到“未修改”状态。

I would actually create a method updateSaveState() containing that code and have both save and the modified callback call updateSaveState() , removing the duplicated code there and putting all the logic for window title etc in one place. 我实际上将创建一个包含该代码的方法updateSaveState() ,并保存和修改后的回调调用updateSaveState() ,在此删除重复的代码,并将窗口标题等的所有逻辑都放在一个位置。

I'd also be tempted to create an isModified() method that returns !textArea.getText.equals(lastSaved) and remove the saved flag completely. 我也很想创建一个isModified()方法,该方法返回!textArea.getText.equals(lastSaved)并完全删除保存的标志。 Anything that wants to know can just call isModified() . 任何想知道的内容都可以调用isModified()

Note that in this case the edit will not be applied yet at the point the keyTyped is received. 请注意,在这种情况下,在收到keyTyped时将不会应用编辑。 If you do a SwingUtilities.invokeLater to delay your processing until after the keypress has been processed that should fix this problem. 如果您执行SwingUtilities.invokeLater来延迟您的处理,直到处理完按键之后,这应该可以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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