2015-05-17 4 views
0

У меня есть рабочий класс HoltWinters, который является основным в моем пакете. Это консольное приложение. Я просматриваю одну папку на своем компьютере, читаю имена всех файлов в этой папке. Затем я прошу пользователя напечатать имя файла, который он хочет использовать в программе. После этого я сохраняю это имя как строку и использую этот файл для прогноза.Как перевести консольное приложение в среду SWING?

Но мне нужно сделать это с помощью приложения Windows. Как я понимаю, мне нужно создать новый java JFrame (я использую NetBeans, поэтому я сделал с помощью своего конструктора). Я положил туда 1 поле JText и 1 JButton. Я хочу, чтобы следующие вещи происходит, когда я нажимаю кнопку:

  1. текст из поля JText считывается и сохраняется в виде строки
  2. метод HoltWinters.main выполняется, используя строки из JText

Но я не понимаю, как это сделать вообще :(Думаю, может быть, я ошибаюсь в своей логике или это нужно делать по-другому, но это мое первое не консольное приложение, и я не знаю, что делать :-(

Это мой класс HoltWinters:

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]); 
    } 
} 

}

Это JFrame

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     
} 
+0

Можете ли вы показать код, в котором вы создаете 'JFrame' и другие компоненты, о которых вы говорите? – CKing

+0

Я отредактировал сообщение –

+3

Прежде чем делать какое-либо создание графического интерфейса, вы должны изменить и улучшить свою консольную программу. В настоящее время это не более чем один * огромный * статический основной метод с несколькими другими более статическими методами, и нет никакого способа, чтобы что-то такое структурированное можно безопасно портировать в графический интерфейс. То, что вы хотите сделать, - создать истинные классы, совместимые с ООП, классы с состояниями (нестатические поля экземпляра) и поведения (нестатические методы), классы, которые будут представлять собой *** программу *** вашей программы ***. Затем проверьте эти классы, используя их в консольной программе, и если они протестируют «ОК», попробуйте создать графический интерфейс, который их использует. –

ответ

0
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); 
      } 

вам нужно изменить код много, начните с дао, модели и графического интерфейса слоев (пакетов).

Смежные вопросы