gpt4 book ai didi

java - 在不同类的 JTextArea (java) 中加载文本文件

转载 作者:行者123 更新时间:2023-12-01 10:20:52 25 4
gpt4 key购买 nike

我在 netbeans 中遇到一个项目问题:我主要上课:

CLASS MainFrame

...
Model m = null;
File f;
String filename = "";
String specific = readSpecification();
private void openModelActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
chooser.setFileFilter(filter);
chooser.showOpenDialog(null);
f = chooser.getSelectedFile();
filename = f.getAbsolutePath();
PrincipalFrame prFrame1 = new PrincipalFrame();

prFrame1.setVisible(true);


}



public String readSpecification() {

String spec = "";
/**
* Reads the model specification from file.
*
* @return a <code>String</code> with the model specification
*/
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
while(line!=null) {
spec += line + "\n";
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return spec;
}

}

PrincipalFrame 类大部分是空的。

MainFrame 类应选择要打开的 file.txt。PrimaryFrame 类有一个 JTextArea,应使用 MainFrame 类选择的 txt 来实现。换句话说,在MainFrame打开的第一刻,用户应该选择一个txt文件。一旦他选择了它,PrincipalFrame 就会出现,并且它的 JTextArea 应该已经用 file.txt 填充了。希望现在一切都清楚了!感谢您的帮助!

最佳答案

您可以在 PrincipalFrame 类中创建一个 setSpecification 方法来填充 JTextArea。通过这种方式,您可以将规范文本从 MainFrame 传递到 PrincipalFrame 类。例如:

MainFrame.java:

public class MainFrame {
// [...]

private void openModelActionPerformed(java.awt.event.ActionEvent evt) {
// [...]
filename = f.getAbsolutePath();
PrincipalFrame prFrame1 = new PrincipalFrame();
prFrame1.setSpecification(readSpecification());
prFrame1.setVisible(true);
}

// [...]
}

PrincipalFrame.java:

public class PrincipalFrame {
private JTextArea textArea;

// [...]

public void setSpecification(String specification) {
textArea.setText(specification);
}
}

关于java - 在不同类的 JTextArea (java) 中加载文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com