[英]How to access text of JTextArea of one class (or .java file) in Applet?
[英]Load a text file in a JTextArea (java) in a different class
我在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。 PrincipalFrame類具有JTextArea,應使用MainFrame類選擇的txt來實現。 換句話說,首先打開MainFrame,用戶應該選擇一個txt文件。 一旦選擇它,就會顯示PrincipalFrame,並且應該使用file.txt來實現其JTextArea。 希望現在清楚了! 謝謝你的幫助!
您可以在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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.