我如何从JText读取文本到同一类的主方法



我不明白。

我需要从JText字段获取文本?将其保存为字符串,稍后在同一类的main方法中使用它。我弄错了

非静态变量文件不能从静态上下文中引用

但是main方法必须保持静态,并且它不能对字段做任何操作,因为它使用标准NetBeans工具来制作JFrame应用程序。

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    String name = jTextField1.getText();
     file = new File( path+"\"+name+".txt" );
} 

请帮忙!

注:这是整个类

package holtwinters;
import static holtwinters.HoltWinters.sum;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;

public class NewJFrame extends javax.swing.JFrame {
/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();
}
String path = "C:\Users\Jane\Desktop";
File file;

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("Введите номер банкомата");
    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });
    jButton1.setText("Ввести");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(25, 25, 25)
            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(136, 136, 136)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
            .addContainerGap(141, Short.MAX_VALUE))
    );
    pack();
}// </editor-fold>                        
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    String name = jTextField1.getText();
     file = new File( path+"\"+name+".txt" );
}                                           
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        
/**
 * @param args the command line arguments
 */
 /*  public void run(){
        String name = jTextField1.getText();
}
  */ 
public static void main(String args[]) 
throws FileNotFoundException, IOException{
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    new NewJFrame();

//    new NewJFrame().run();
    new NewJFrame().jTextField1ActionPerformed(null);

    BufferedReader br = new BufferedReader (
            new InputStreamReader(
                    new FileInputStream( file ), "UTF-8"
            )
    );
    String line = null;
    while ((line = br.readLine()) != null) {

        try {
            Long y = Long.valueOf(line);
           // System.out.println(y);
        } catch (NumberFormatException e) {
            System.err.println("Неверный формат строки!");
        }
    }
  //  long data = Long.valueOf(line);
  //  int change = (int) data;
  //  long [] y = new long [change];
    int period = 24;
    int m = 5;
    long[] y = new long[144];
    try {
        Scanner scanner = new Scanner(new File(path+"\"+name+".txt"));
        int i = 0;
        while (scanner.hasNextLong()) {
            y[i] = scanner.nextLong();
            i++;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    double sum_origin = 0;
    int k=0;
    do {
        sum_origin = sum_origin + y[k];
        k++;
    } while (k<24);
//searching for alpha
    double alpha = 0.01;
    double a = 0.01;
    double x=sum_origin;
    double q;
    do {
        double beta = 0.3;
        double gamma = 0.3;
        double[] prediction = HoltWinters.forecast(y, a, beta, gamma,
                period, m);
        double sum_pre = sum(prediction);
          q = sum_origin - sum_pre;
        if (q<=x) {
            x=q;
            alpha = a;
        }
        a = a +0.01;
    } while (a<0.99);
//searching for beta
    double beta = 0.01;
    double b = 0.01;
    double x1=1000000;
    double q1;
    do {
        double gamma = 0.3;
        double[] prediction = HoltWinters.forecast(y, alpha, b, gamma,
                period, m);
        double sum_pre = sum(prediction);
        q1 = sum_origin - sum_pre;
        if (q1<=x1) {
            x1=q1;
            beta = b;
        }
        b = b +0.01;
    } while (b<0.99);
//searching for gamma
    double gamma = 0.01;
    double g = 0.01;
    double x2=1000000;
    double q2;
    do {
        double[] prediction = HoltWinters.forecast(y, alpha, beta, g,
                period, m);
        double sum_pre = sum(prediction);
        q2 = sum_origin - sum_pre;
        if (q2<=x2) {
            x2=q2;
            gamma = g;
        }
        g = g +0.01;
    } while (g<0.99);

  //  System.out.println(alpha);
  //  System.out.println(beta);
  //  System.out.println(gamma);

    double[] prediction = HoltWinters.forecast(y, alpha, beta, gamma,
            period, m);
   for(int i = period; i <= prediction.length - 1; i++) {
           System.out.println(prediction[i] + "  ");
    }
    br.close();

    File flt = new File("C:\Users\Jane\Desktop\"+name+"_prediction.txt");
    PrintWriter out = new PrintWriter(new BufferedWriter(
            new FileWriter(flt)));
    for(int i = period; i <= prediction.length - 1; i++) {
        out.println(prediction[i] + "  ");
    }
    out.flush();

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   
}

我认为你想从程序中做的是:

  • 一旦用户界面被初始化,您想要从用户(通过JTextField)获取一些输入,该输入应该是文件名
  • 通过读取文件名,你想要构建file对象。

如果我认为你想要的是正确的,那么你可以通过使用按钮的click事件也实现而不是使用匿名内部类按钮动作监听器,你可以实现接口在你的类NewJFrame本身和验证JTextField值在actionPerformed()和委托实际逻辑在一些其他方法。

只将main方法用作程序的n入口点。像initComponents()一样,您可以创建方法来执行业务逻辑、读取文件和创建对用户操作的响应。这样,程序将易于阅读和维护。

同样,main()中使用的new NewJFrame().jTextField1ActionPerformed(null);也没有意义。在程序中应该只初始化JFrame一次。我认为你应该在你的main()方法中只写一个语句

new JFrame();

这将启动你的程序,然后你的程序必须由用户操作驱动。

希望对大家有所帮助

错误在这里:

BufferedReader br = new BufferedReader (
        new InputStreamReader(
                new FileInputStream( file ), "UTF-8"
        )
);

file是一个实例变量,不能从静态方法访问。必须在文件变量前加上static关键字。

static File file;
不是

File file;

相关内容

  • 没有找到相关文章

最新更新