这是我的小应用程序代码的一部分,我在第 50 行和第 85 行肯定有语法错误,任何人都可以帮助我解决这个问题并与您核实。这个应用程序只做一件事,单击按钮时,您需要选择 txt 文件,该应用程序将读取并更改一个单词而不是另一个单词,并且应该使用相同的名称保存它:
public void initListeners() {
chooseFile.addActionListener(e)-> {
JFileChooser fs = new JFileChooser(new File("C:\\"));
fs.setDialogTitle("Choose document to change");
fs.setFileFilter(new FileTypeFilter(".txt", " New Text Document"));
int result = fs.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
BufferedReader br;
String fulltext = " ";
try {
File fi = fs.getSelectedFile();
br = new BufferedReader(new FileReader(fi.getPath()));
String line;
int i = 0;
while ((line = br.readLine()) != null) {
fulltext += line + "\r\n";
}
br.close();
fulltext = fulltext.replace("tekst", "cs101");
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
PrintWriter upis;
try {
upis = new PrintWriter("C:\\Users\\Maksimovic\\Desktop\\tekstzaobradu.txt");
upis.append(fulltext);
upis.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
};
}
最佳答案
更改:
.addActionListener(ActionEvent e)-> {
至
.addActionListener(e -> {
使用 lambda 快捷方式时,您不需要也不应该提供参数的类型。至于第 85 行,您需要更好地格式化代码以便我们理解它。
编辑,85 需要一个右括号来结束 addActionListener
方法调用。
public void initListeners(){
chooseFile.addActionListener(e -> {
JFileChooser fs=new JFileChooser(new File("C:\\"));
fs.setDialogTitle("Choose document to change");
fs.setFileFilter(new FileTypeFilter(".txt"," New Text Document"));
int result=fs.showOpenDialog(null);
if(result==JFileChooser.APPROVE_OPTION){
BufferedReader br;
String fulltext=" ";
try {
File fi=fs.getSelectedFile();
br=new BufferedReader(new FileReader(fi.getPath()));
String line;
int i=0;
while((line=br.readLine())!=null){
fulltext+=line+"\r\n";
}
br.close();
fulltext=fulltext.replace("text","cs101");
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage() );
}catch(IOException ex){
JOptionPane.showMessageDialog(null, ex.getMessage() );
}
PrintWriter input;
try {
upis=new PrintWriter(new FileWriter(fi.getPath));
upis.append(fulltext);
upis.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage() );
}
}
});
}
旁注:如果这是我的项目,我会将大部分代码放在自己的方法中,以简化并更轻松地进行调试。
例如,
public void initListeners(){
chooseFile.addActionListener(e -> chooseFileActionPerformed());
}
还可以考虑使用 AbstractActions 来代替 ActionListeners。这可以帮助您将程序逻辑与 View 分离。
附带问题:您的文件输入和输出代码应该在 Swing 事件线程之外并在其自己的后台工作线程(例如由 SwingWorker 提供)中完成。这应该会使您的 GUI 响应更快。
关于java - ActionListener 的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42813266/