2016-11-24 92 views
1

因此,我花了一個小時試圖弄清楚如何從GUI打開這個文件,但每次我點擊打開的文件,然後單擊他想要打開的文件,我的GUI只是崩潰。在這裏,我的代碼請告訴我什麼是錯的。 這是給我的,所以它不會錯。java打開文件從GUI襤褸陣列雙打

import java.io.File; 
import java.io.FileNotFoundException; 
import java.text.NumberFormat; 

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.control.Tooltip; 
import javafx.stage.FileChooser; 
import javafx.stage.Stage; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.layout.GridPane; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.VBox; 
import javafx.scene.paint.Color; 
import javafx.scene.text.Font; 

public class MvGuiFx extends Application {; 
    private double[][] sales; 
    public static final int MAX_STORES = 6; 
    public static final int MAX_ITEMS = 6; 
    private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); 
    Button readFileBtn, exitBtn; 
    GridPane dataPane; 


    /** 
    * Lets the user choose a file to read the sales information and displays 
    * the information on the screen 
    * @throws FileNotFoundException 
    */ 
    public void readFile() throws FileNotFoundException { 
     File selectedFile; 

     FileChooser chooser = new FileChooser(); 
     chooser.setTitle("Choose a file to read retail items' sales information"); 
     if ((selectedFile = chooser.showOpenDialog(null)) != null) { 
      // Read the file 
      sales = TwoDimRaggedArrayUtility.readFile(selectedFile); 
     } 
     //display on the screen 
     int row,col; 
     double total; 
     for(row=0;row<sales.length; row++) 
      for(col=0;col<sales[row].length;col++) 
       dataPane.add(new TextField(currencyFormat.format(sales[row][col])),col+1,row+1); 

     //display row totals 
     for(row=0;row<sales.length;row++) 
     { 
      total = TwoDimRaggedArrayUtility.getRowTotal(sales, row); 
      dataPane.add(new TextField(currencyFormat.format(total)), 7, row+1); 
     } 

     //find the row with largest number of columns 
     int columns = 0; 
     for(row=0;row<sales.length;row++) 
      if(sales[row].length > columns) columns = sales[row].length; 

     //display column totals 
     for(col=0;col<columns;col++) 
     { 
      total = TwoDimRaggedArrayUtility.getColumnTotal(sales, col); 
      dataPane.add(new TextField(currencyFormat.format(total)), col+1, 7); 
     } 

     //find highest in each column 
     for(col=0;col<columns;col++) 
     { 
      total = TwoDimRaggedArrayUtility.getHighestInColumn(sales, col); 
      TextField temp = new TextField(currencyFormat.format(total)); 
      temp.setStyle("-fx-background-color: gray;"); 
      for(row=0;row<sales.length;row++) { 
       if(col < sales[row].length){ 
        if(sales[row][col]==total) 
         dataPane.add(temp, col+1, row+1); 
       } 
      } 
     } 


} 

    // Handler class. 
    private class ButtonEventHandler implements EventHandler<ActionEvent> { 
     @Override 
     public void handle(ActionEvent e) { 
      //handler for Load Sales Data 
      if (e.getSource() == readFileBtn) { 

       try { 
        readFile(); 
       } catch (FileNotFoundException e1) { 
        e1.printStackTrace(); 
       } 

      //handler for Exit button 
      } else if (e.getSource() == exitBtn) 

       System.exit(0); 
     } 
    } 

    @Override 
    public void start(Stage stage) { 

     Tooltip buttonToolTipArr[] = new Tooltip[5]; 
     buttonToolTipArr[0] = new Tooltip(
       "Load sales data from a file and Display"); 
     buttonToolTipArr[1] = new Tooltip("Exit Application"); 

     // Main Pane 
     BorderPane MainPane = new BorderPane(); 

     // Create Title Pane, add title label and add it to the top of the Main 
     // Pane 
     HBox titlePanel = new HBox(); 
     titlePanel.setAlignment(Pos.BASELINE_CENTER); 
     Label titleLbl = new Label("DisneyWorld District 5 Sales Report\n"); 
     titleLbl.setFont(new Font(30)); 
     titleLbl.setTextFill(Color.BLUE); 

     titlePanel.getChildren().add(titleLbl); 
     MainPane.setTop(titlePanel); 

     // CenterPane 
     VBox centerPane = new VBox(); 
     centerPane.setAlignment(Pos.CENTER); 

     // columnHeader Pane 
     HBox columnHeaderPane = new HBox(10); 
     columnHeaderPane.setAlignment(Pos.CENTER); 


     int i,j; 
     dataPane = new GridPane(); 
     dataPane.setAlignment(Pos.BASELINE_CENTER); 
     dataPane.add(new Label("  "), 0, 0); 
     dataPane.add(new Label("Books"), 1, 0); 
     dataPane.add(new Label("Tsum Tsum"), 2, 0); 
     dataPane.add(new Label("Trading Pins"), 3, 0); 
     dataPane.add(new Label("Star Wars"), 4, 0); 
     dataPane.add(new Label("Lego"), 5, 0); 
     dataPane.add(new Label("Marvel"), 6, 0); 
     dataPane.add(new Label("Total"), 7, 0); 

     for(i=1;i<8;i++) 
     { 
      dataPane.add(new Label("  "), 0,i); 
      for(j = 1; j<8;j++) 
       dataPane.add(new TextField(), i,j); 
     } 


     dataPane.add(new Label("Emporium"), 0, 1); 
     dataPane.add(new Label("World Traveler"), 0, 2); 
     dataPane.add(new Label("Discovery Trading Center"), 0, 3); 
     dataPane.add(new Label("Merchant of Venus"), 0, 4); 
     dataPane.add(new Label("Once Upon a Toy"), 0, 5); 
     dataPane.add(new Label("Tatooine Traders"), 0, 6); 
     dataPane.add(new Label("Total"), 0, 7); 

     // Create bottom Pane 
     HBox bottomPane = new HBox(10); 
     bottomPane.setAlignment(Pos.BASELINE_CENTER); 

     // Create buttons 
     readFileBtn = new Button("Load Sales Data"); 
     readFileBtn.setTooltip(buttonToolTipArr[0]); 
     exitBtn = new Button("Exit"); 
     exitBtn.setTooltip(buttonToolTipArr[1]); 

     // add event handler to buttons 
     readFileBtn.setOnAction(new ButtonEventHandler()); 
     exitBtn.setOnAction(new ButtonEventHandler()); 

     // add buttons to bottomPane 
     bottomPane.getChildren().addAll(readFileBtn, exitBtn); 
     MainPane.setBottom(bottomPane); 

     // add panes to center pane 
     centerPane.getChildren().addAll(dataPane); 

     MainPane.setCenter(centerPane); 

     Scene scene = new Scene(MainPane, 1200, 400); 
     stage.setScene(scene); 

     // Set stage title and show the stage. 
     stage.setTitle("District Sales Report"); 
     stage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

繼承人是我到目前爲止有:

import java.io.PrintWriter; 
import java.util.Scanner; 

public class TwoDimRaggedArrayUtility { 

    public TwoDimRaggedArrayUtility() 
    { 

    } 

    public static double[][] readFile(java.io.File file) throws java.io.FileNotFoundException 
    { 

     Scanner scan = new Scanner(file); 
     int row = 0; 

     while(scan.hasNextLine()) 
     { 
      row++; 
     } 

     double[][] array = new double[row][]; 

     for(int index = 0; index < array[0].length; index++) 

       array[0] = new double[index]; 

     for(int index = 0; index < array[1].length; index++) 

       array[1] = new double[index]; 

     for(int index = 0; index < array[2].length; index++) 

       array[2] = new double[index]; 

     for(int index = 0; index < array[3].length; index++) 

       array[3] = new double[index]; 

     for(int index = 0; index < array[4].length; index++) 

       array[4] = new double[index]; 

     for(int index = 0; index < array[5].length; index++) 

       array[5] = new double[index]; 

     for(int index = 0; index < array[6].length; index++) 

       array[6] = new double[index]; 

     for(int index = 0; index < array[7].length; index++) 

       array[7] = new double[index]; 

     for(int index = 0; index < array[8].length; index++) 

       array[8] = new double[index]; 

     for(int index = 0; index < array[9].length; index++) 

       array[9] = new double[index]; 

     for(int index = 0; index < array[10].length; index++) 

       array[10] = new double[index]; 

     scan.close(); 

     return array; 
    } 

    public static void writeToFile(double[][] data, java.io.File outputFile)throws java.io.FileNotFoundException 
    { 
     PrintWriter print = new PrintWriter(outputFile); 
     print.print(data); 
     print.close(); 
    } 

而這裏的衣衫襤褸的數組.txt文件:

1253.65 4566.50 2154.36 7532.45 3388.44 6598.23 
2876.22 3576.24 1954.66 
4896.23 2855.29 2386.36 5499.29 
2256.76 3623.76 4286.29 5438.48 3794.43 
3184.38 3654.65 3455.76 6387.23 4265.77 4592.45 
2657.46 3265.34 2256.38 8935.26 5287.34 

回答

1

我要誠實,有一個公平的位錯與您的代碼。

一方面,你完全避免使用GUI。如果一切順利,應該在你的文件中讀取並打印出內容

public static void main(String[] args) throws Exception { 
    double[][] sales = readFile(new java.io.File("path/to/your/file")); 
    for (double[] row : sales) { 
     System.out.println(java.util.Arrays.toString(row)); 
    } 
} 

:如果您添加以下main方法TwoDimRaggedArrayUtility,那麼你可以直接不啓動圖形用戶界面運行這個類。首先,你的代碼並沒有太多的崩潰(即停止了一個令人討厭的錯誤),它實際上是掛起的(看起來無所事事就停滯不前)。

while(scan.hasNextLine()) 
    { 
     row++; 
    } 

這是什麼呢:通過採取看看這個循環

讓我們開始?

答案如下:雖然在掃描儀中有下一行,但可以加一個到row

請注意,您從任何時候都不會讀取掃描儀的任何行。所以如果掃描儀中有任何文本,這個循環將永遠運行,無休止地增加row

要從掃描儀讀取一條線,請致電其nextLine()方法。使用掃描儀時,通常在讀取數據之前檢查其中是否有數據。因此,我們現在有:

while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 
     row++; 
    } 

如果我們對您的代碼進行此更改,則不會再掛起。它讀取文件中的所有行。然而,後來又把這條線一NullPointerException

for (int index = 0; index < array[0].length; index++) 

要理解爲什麼,我們需要看一看前行:

double[][] array = new double[row][]; 

這是什麼呢?它創建一個包含6個元素的數組,因爲row在完成while循環後以6結尾。但是,數組中的每個元素(即每個'內部'數組')都是null,因爲您沒有爲內部數組指定大小。所以當你試圖讀取其中一個數組的長度時,你會得到一個NullPointerException,因爲沒有數組要讀取長度。

暫且擱置這一點,假設array[0].length返回,例如4。然後,我們可以預期接下來的循環中運行四次:

for (int index = 0; index < array[0].length; index++) 

     array[0] = new double[index]; 

的這裏的問題是,這個循環(與index零)的第一次迭代然後設置array[0]是一個空數組。下一次循環index爲1,但array[0].length現在爲0,因此循環結束。

這個循環不是非常有用,因爲它只運行一次,如果我們能夠運行它,它只是創建一個空數組double s並將其放入array[0]。這個循環以及其他十個循環都不值得保留,所以讓我們把它們全部刪除。

讓我們回到while循環頂部:

while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 
     row++; 
    } 

我們仍然沒有做與line任何正在讀我們希望它分裂成號碼,並閱讀。所有在目前,我們正在使用掃描儀分割文件到線,我們其實可以使用其他掃描儀行拆分成數字:

while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 

     int column = 0; 
     Scanner doubleScanner = new Scanner(line); 
     while (doubleScanner.hasNextDouble()) { 
      double value = doubleScanner.nextDouble(); 
      column++; 
     } 

     row++; 
    } 

注意五大行我已經插入類似於while我們開始的循環。我們在閱讀之前檢查是否有其他double要從雙打掃描儀中讀出,就像我們在閱讀線路時一樣。

這讓我們更接近。不過,儘管我們正在閱讀行掃描儀的double值,但我們仍然沒有將它們存儲在任何地方。

不幸的是,這是事情變得有點煩躁的地方。 Java的數組是不靈活的,因爲一旦你創建了它們,你就不能改變它們的大小。如果你想使一個數組變大或變小,你必須創建一個所需大小的新數組並將其複製。爲了簡單起見,並且因爲這看起來像是一個類分配而不是實際的生產代碼,我們假設最多有10行和10列。因此,我們可以通過修改我們的代碼存儲在一個數組中的值:

double[][] array = new double[10][10]; 
    while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 
     int column = 0; 
     Scanner doubleScanner = new Scanner(line); 
     while (doubleScanner.hasNextDouble()) { 
      array[row][column] = doubleScanner.nextDouble(); 
      ++column; 
     } 

     row++; 
    } 

我添加一行創建陣列,並調整讀取double今晚出doubleScanner行。請注意,new double[10][10]是一個由10個數組組成的數組,每個內部數組有10個元素,全部初始化爲零。

在這一點上,我們現在應該能夠運行代碼並顯示一些輸出。但是,結果並不完全符合我們的要求,因爲行和列都填充了零以使它們達到10乘10。解決這個問題的最簡單方法可能是使用Arrays.copyOfRange()方法來創建我們感興趣的數組部分的副本,並用副本替換原始數據。我們需要爲每一行做一次,一旦整個數組:

double[][] array = new double[10][10]; 
    while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 
     int column = 0; 
     Scanner doubleScanner = new Scanner(line); 
     while (doubleScanner.hasNextDouble()) { 
      array[row][column] = doubleScanner.nextDouble(); 
      ++column; 
     } 

     array[row] = java.util.Arrays.copyOfRange(array[row], 0, column); 
     row++; 
    } 

    array = java.util.Arrays.copyOfRange(array, 0, row); 

最後,返回我們想要的數據,沒有任何填充零。

由於這是一個(懷疑)類分配,請花時間瞭解此代碼正在執行的操作以及它的工作原理。使用軟件,理解很重要。不要盲目地將代碼從互聯網上覆制,而不理解它的功能。