2016-11-24 85 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); 

最后,返回我们想要的数据,没有任何填充零。

由于这是一个(怀疑)类分配,请花时间了解此代码正在执行的操作以及它的工作原理。使用软件,理解很重要。不要盲目地将代码从互联网上复制,而不理解它的功能。