Java 如何将控制台应用程序转换为SWING框架?

Java 如何将控制台应用程序转换为SWING框架?,java,swing,console,jframe,Java,Swing,Console,Jframe,我有一个工人阶级的Holtwiners,这是我的主要包装。它是一个控制台应用程序。我搜索计算机上的一个文件夹,读取该文件夹中所有文件的名称。然后我要求用户打印他想在程序中使用的文件名。之后,我将此名称保存为字符串,并将此文件用于预测 但我需要通过windows应用程序来完成。据我所知,我需要创建新的JavaJFrame(我使用NetBeans,所以我已经使用了它们的构造函数)。我在那里放了1个JText字段和1个JButton。我想在按下按钮时发生下一件事: JText字段中的文本将被读取并保存

我有一个工人阶级的Holtwiners,这是我的主要包装。它是一个控制台应用程序。我搜索计算机上的一个文件夹,读取该文件夹中所有文件的名称。然后我要求用户打印他想在程序中使用的文件名。之后,我将此名称保存为字符串,并将此文件用于预测

但我需要通过windows应用程序来完成。据我所知,我需要创建新的JavaJFrame(我使用NetBeans,所以我已经使用了它们的构造函数)。我在那里放了1个JText字段和1个JButton。我想在按下按钮时发生下一件事:

  • JText字段中的文本将被读取并保存为字符串
  • 使用JText中的字符串运行holtwiners.main方法
  • 但我一点也不明白该怎么做:(我想,也许我的逻辑有点错误,或者应该换一种方式来做,但这是我的第一个非控制台应用程序,我不知道该怎么做:-(

    这是我的Holtwiners课程:

    package holtwinters;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    /**
    St[i] = alpha * y[i] / It[i - period] + (1.0 - alpha) * (St[i - 1] + Bt[i - 1]) - overall
    Bt[i] = gamma * (St[i] - St[i - 1]) + (1 - gamma) * Bt[i - 1] - trend
    It[i] = beta * y[i] / St[i] + (1.0 - beta) * It[i - period] - season
    Ft[i + m] = (St[i] + (m * Bt[i])) * It[i - period + m] - predictions
    */
    
    /**
    *
    * @author Jane
    */
    public class HoltWinters {
    
    /**
     * @param args the command line arguments
     */
      /*
     y - Time series data.
     alpha - coeff
     beta - coeff
     gamma - coeff
     period - 24 hours
     m - future data
     debug -  debug values for testing
     */
    
    public static void main( String[] args )
            throws FileNotFoundException, IOException {
    
        String path = "C:\\Users\\Jane\\Desktop";
    
        File f = new File (path);
        String[] list=f.list();
        for (String str : list){
            System.out.println(str);
        }
    
        BufferedReader in=new BufferedReader (new InputStreamReader(System.in));
        System.out.print("Input n: ");
        String sn=in.readLine();
        String[] ary = sn.split(" ");
        String name = null;
    
    
        for(String file1: list) {
            for (String ary1: ary) {
                if (ary1.equals(file1)) {
                    System.out.println("found!");
                    name = sn;
    
                }
            }
        }
    
        File file = new File( path+"\\"+name );
    
        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));
    
            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\\003003_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();
    
    
    }
    
    
    public static double sum(double...values) {
        double result = 0;
        for (double value:values)
            result += value;
        return result;
    }
    
    
    
    public static double[] forecast(long[] y, double alpha, double beta,
                                    double gamma, int period, int m, boolean debug) {
    
    
    
    
        validateArguments(y, alpha, beta, gamma, period, m);
    
        int seasons = y.length / period;
        double a0 = calculateInitialLevel(y, period);
        double b0 = calculateInitialTrend(y, period);
        double[] initialSeasonalIndices = calculateSeasonalIndices(y, period,
                seasons);
    
        if (debug) {
            System.out.println(String.format(
                    "Total observations: %d, Seasons %d, Periods %d", y.length,
                    seasons, period));
            System.out.println("Initial level value a0: " + a0);
            System.out.println("Initial trend value b0: " + b0);
            printArray("Seasonal Indices: ", initialSeasonalIndices);
        }
    
        double[] forecast = calculateHoltWinters(y, a0, b0, alpha, beta, gamma,
                initialSeasonalIndices, period, m, debug);
    
        if (debug) {
            printArray("Forecast", forecast);
        }
    
        return forecast;
    }
    
    public static double[] forecast(long[] y, double alpha, double beta,
                                    double gamma, int period, int m) {
        return forecast(y, alpha, beta, gamma, period, m, false);
    }
    
    /**
     validate input
     */
    private static void validateArguments(long[] y, double alpha, double beta,
                                          double gamma, int period, int m) {
        if (y == null) {
            throw new IllegalArgumentException("Value of y should be not null");
        }
    
        if(m <= 0){
            throw new IllegalArgumentException("Value of m must be greater than 0.");
        }
    
        if(m > period){
            throw new IllegalArgumentException("Value of m must be <= period.");
        }
    
        if((alpha < 0.0) || (alpha > 1.0)){
            throw new IllegalArgumentException("Value of Alpha should satisfy 0.0 <= alpha <= 1.0");
        }
    
        if((beta < 0.0) || (beta > 1.0)){
            throw new IllegalArgumentException("Value of Beta should satisfy 0.0 <= beta <= 1.0");
        }
    
        if((gamma < 0.0) || (gamma > 1.0)){
            throw new IllegalArgumentException("Value of Gamma should satisfy 0.0 <= gamma <= 1.0");
        }
    }
    
    /**
     the Holt-Winters equations
     */
    private static double[] calculateHoltWinters(long[] y, double a0, double b0,
                                                 double alpha, double beta, double gamma,
                                                 double[] initialSeasonalIndices, int period, int m, boolean debug) {
    
        double[] St = new double[y.length];
        double[] Bt = new double[y.length];
        double[] It = new double[y.length];
        double[] Ft = new double[y.length + m];
    
        // Initialize base values
        St[1] = a0;
        Bt[1] = b0;
    
        for (int i = 0; i < period; i++) {
            It[i] = initialSeasonalIndices[i];
        }
    
        // Start calculations
        for (int i = 2; i < y.length; i++) {
    
            // Calculate overall smoothing
            if ((((i - period) >= 0) & (It[i]!=0))) {
                St[i] = alpha * y[i] / It[i - period] + (1.0 - alpha)
                        * (St[i - 1] + Bt[i - 1]);
            }
            else {
                St[i] = alpha * y[i] + (1.0 - alpha) * (St[i - 1] + Bt[i - 1]);
            }
    
            // Calculate trend smoothing
            Bt[i] = gamma * (St[i] - St[i - 1]) + (1 - gamma) * Bt[i - 1];
    
            // Calculate seasonal smoothing
            if ((i - period) >= 0) {
                It[i] = beta * y[i] / St[i] + (1.0 - beta) * It[i - period];
            }
    
            // Calculate forecast
            if (((i + m) >= period)) {
                Ft[i + m] = Math.abs(((St[i] + (m * Bt[i])) * It[i - period + m])*(-1));
            }
    
            if (debug) {
                System.out.println(String.format(
                        "i = %d, y = %d, S = %f, Bt = %f, It = %f, F = %f", i,
                        y[i], St[i], Bt[i], It[i], Ft[i]));
            }
        }
        return Ft;
    }
    
    /**
     Initial Level value - St[1]
     */
    public static double calculateInitialLevel(long[] y, int period) {
        double sum = 0;
    
        for (int i = 0; i < 24; i++) {
            sum += (y[i]);
        }
        return sum / (period*period);
    }
    
    /**
     Initial trend - Bt[1]
     */
    public static double calculateInitialTrend(long[] y, int period) {
    
        double sum = 0;
    
        for (int i = 0; i < period; i++) {
            sum += Math.abs((y[period + i] - y[i]));
        }
        return sum / (period * period);
    }
    
    /**
     Seasonal Indices.
     */
    public static double[] calculateSeasonalIndices(long[] y, int period,
                                                    int seasons) {
    
        double[] seasonalAverage = new double[seasons];
        double[] seasonalIndices = new double[period];
    
        double[] averagedObservations = new double[y.length];
    
        for (int i = 0; i < seasons; i++) {
            for (int j = 0; j < period; j++) {
                seasonalAverage[i] += y[(i * period) + j];
            }
            seasonalAverage[i] /= period;
        }
    
        for (int i = 0; i < seasons; i++) {
            for (int j = 0; j < period; j++) {
                averagedObservations[(i * period) + j] = y[(i * period) + j]
                        / seasonalAverage[i];
            }
        }
    
        for (int i = 0; i < period; i++) {
            for (int j = 0; j < seasons; j++) {
                seasonalIndices[i] += averagedObservations[(j * period) + i];
            }
            seasonalIndices[i] /= seasons;
        }
    
        return seasonalIndices;
    }
    
    /**
     method to print array values
     */
    private static void printArray(String description, double[] data) {
        System.out.println(description);
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }
    
    packageholtwiners;
    导入java.io.*;
    导入java.util.*;
    导入java.lang.*;
    /**
    St[i]=alpha*y[i]/It[i-周期]+(1.0-α)*(St[i-1]+Bt[i-1])-总体
    Bt[i]=伽马*(St[i]-St[i-1])+(1-伽马)*Bt[i-1]-趋势
    It[i]=beta*y[i]/St[i]+(1.0-beta)*It[i-period]-季节
    Ft[i+m]=(St[i]+(m*Bt[i])*It[i-周期+m]-预测
    */
    /**
    *
    *@作者简
    */
    公营Holtwiners{
    /**
    *@param指定命令行参数
    */
    /*
    y-时间序列数据。
    阿尔法系数
    贝塔系数
    伽马系数
    期间-24小时
    m-未来数据
    调试-用于测试的调试值
    */
    公共静态void main(字符串[]args)
    抛出FileNotFoundException,IOException{
    String path=“C:\\Users\\Jane\\Desktop”;
    文件f=新文件(路径);
    字符串[]list=f.list();
    for(字符串str:list){
    系统输出打印项次(str);
    }
    BufferedReader in=新的BufferedReader(新的InputStreamReader(System.in));
    系统输出打印(“输入n:”);
    字符串sn=in.readLine();
    字符串[]ari=sn.split(“”);
    字符串名称=null;
    用于(字符串文件1:列表){
    for(字符串ary1:ary){
    if(ary1.equals(file1)){
    System.out.println(“found!”);
    名称=序号;
    }
    }
    }
    文件文件=新文件(路径+“\\”+名称);
    BufferedReader br=新的BufferedReader(
    新的InputStreamReader(
    新文件输入流(文件),“UTF-8”
    )
    );
    字符串行=null;
    而((line=br.readLine())!=null){
    试一试{
    长y=Long.valueOf(行);
    //系统输出打印项次(y);
    }捕获(数字格式){
    系统错误打印(“ааааааааааааа!”;
    }
    }
    //长数据=长数值(行);
    //int change=(int)数据;
    //长[]y=新长[变更];
    整数周期=24;
    int m=5;
    长[]y=新长[144];
    试一试{
    Scanner Scanner=new Scanner(新文件(路径+“\\”+名称));
    int i=0;
    while(scanner.hasNextLong()){
    y[i]=scanner.nextLong();
    i++;
    }
    }catch(filenotfounde异常){
    e、 printStackTrace();
    }
    双和_原点=0;
    int k=0;
    做{
    sum_origin=sum_origin+y[k];
    k++;
    }while(k
    
    您需要大量更改代码,从dao、模型和gui层(包)开始.

    你能展示一下你创建
    JFrame
    和其他你提到的组件的代码吗?我已经编辑了帖子,在创建任何GUI之前,你必须更改和改进你的控制台程序。目前它只不过是一个巨大的静态主方法和几个其他较小的静态方法,这是不可能的这种结构化的东西可以安全地移植到GUI。您要做的是创建真正符合OOP的类,具有状态(非静态实例字段)和行为(非静态方法)的类,将构成程序模型的类。然后在控制台程序中使用这些类进行测试,如果测试正常,尝试创建一个使用它们的GUI。@JaneMakedonskaya我完全同意Hovercraft。目前的问题对于stackoverflow标准来说太广泛了。@HovercraftFullOfEels我怎么做?也许你可以建议某物??
    package holtwinters;
    
    /**
     *
     * @author Jane
     */
    public class NewJFrame extends javax.swing.JFrame {
    
    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }
    
    /**
     * 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:
    }                                           
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        System.out.println("Button pressed") ;
        HoltWinters other = new HoltWinters();
    
    
    }                                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* 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 
         */
        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                   
    }
    
    yourButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    yourButtonActionPerformed(evt);
                }
            });
    
    
    public void yourButtonActionPerformed(java.awt.event.ActionEvent evt) {
                    String yourText = jTextField1.getText();
                    HoltWinters tempHolt = new HoltWinters();
    
    
      tempHolt.methodToRun(yourText);
                }