繁体   English   中英

将文本文件加载到其他类的JTextArea(java)中

[英]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.

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