尝试动态添加更多按钮到我的JavaFXML项目

时间:2016-03-23 19:28:28

标签: java rest javafx gson fxml

课程要求我们创建一个图表,该图表显示来自JavaFX中服务器的RESTFUL数据。我所拥有的文件是我们从导师那里收到的,他从未真正解释过他是如何取得最终结果的。所以我只是想知道在这个Java Fxml项目中,我是如何编写控制器以添加动态按钮的?

已经调用的按钮是复选框,当它们被选中时,它们会显示条形图中待售的汽车。我想添加按钮,让我选择销售年份,并添加功能到硬编码按钮,从条形图切换到折线图。

FXML代码

<AnchorPane id="" fx:id="AnchorPane1" prefHeight="-1.0"    prefWidth="-1.0"    xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="salescwck3.SalesController">

<children>
  <VBox spacing="10.0">
     <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
     </padding>
     <children>
        <HBox fx:id="HBox1" spacing="10.0">
           <padding>
              <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
           </padding>
        </HBox>
        <HBox fx:id="HBox11" spacing="10.0">
           <padding>
              <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
           </padding>
        </HBox>
        <HBox alignment="TOP_RIGHT" prefHeight="19.0" prefWidth="217.0" spacing="10.0">
           <padding>
              <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
           </padding>
           <children>
              <RadioButton fx:id="RadioButton1" mnemonicParsing="false" text="Bar Chart" />
              <RadioButton fx:id="RadioButton2" mnemonicParsing="false" text="Line Graph" />
           </children>
        </HBox>
        <BarChart fx:id="BarChart1" animated="false" title="Vehicle Sales">
          <xAxis>
            <CategoryAxis label="Region" side="BOTTOM" fx:id="xAxis" />
          </xAxis>
          <yAxis>
            <NumberAxis fx:id="yAxis" label="Quantity of Sales"   side="LEFT" />
          </yAxis>
        </BarChart>
     </children>
  </VBox>
 </children>
</AnchorPane>

主要Java

package salescwck3;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class SalesCwck3 extends Application {    
@Override
public void start(Stage primaryStage) throws Exception {
    Parent root =    FXMLLoader.load(getClass().getResource("SalesController.fxml"));

    Scene scene = new Scene(root);
      scene.getStylesheets().add(SalesCwck3.class.getResource("Style.css").toExternalForm());

    primaryStage.setScene(scene);
    primaryStage.setTitle("SalesCwck3");
    primaryStage.show();
}

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

FXML控制器

public class SalesController implements Initializable {
private static String markup;
private static List<Sales> sales;
private static List<String> vehicles;
private static List<Integer> year;
private DashService service;

private CheckBox[] checkBoxes;

private ChoiceBox[] choiceBoxes;

@FXML
private RadioButton RadioButton1, RadioButton2;    
//Need to learn how to switch from bar chart to line graph

@FXML
private AnchorPane AnchorPane1;

@FXML
private HBox HBox1;
//Contains The Check Boxes constructed for vehicles

@FXML
private HBox HBox2;
//Populate this with the year Choice Box

@FXML
private NumberAxis yAxis;

@FXML
private CategoryAxis xAxis;

@FXML
private BarChart<?, ?> BarChart1;

@Override
public void initialize(URL url, ResourceBundle rb) {
    service = new DashService();
    service.setAddress("http://glynserver.cms.livjm.ac.uk/DashService/SalesGetSales");
    service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            markup = e.getSource().getValue().toString();                
            sales = (new Gson()).fromJson(markup, new TypeToken<LinkedList<Sales>>() {}.getType());


            vehicles = sales.stream().map(o -> o.getVehicle()).distinct().collect(Collectors.toList());
            year = sales.stream().map(o -> o.getYear()).distinct().collect(Collectors.toList());

            // ToDo : Debugging !
            System.out.println(markup);

            for (Sales sale : sales) {
                System.out.println(sale.toString());
            }           

            constructCheckBoxes();


        }
    });



    service.start();
}       

//Need a Progress Loader.



private void constructCheckBoxes() { 
    checkBoxes = new CheckBox[vehicles.size()];

    for (byte index = 0; index < vehicles.size(); index++) {
        checkBoxes[index] = new CheckBox(vehicles.get(index));
        checkBoxes[index].setSelected(true);
        checkBoxes[index].setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {                    

                constructSeries();
            }
        });

        HBox1.getChildren().add(checkBoxes[index]);
    }

    // NOTE : More Controls Visible !
    AnchorPane1.getScene().getWindow().sizeToScene();

    constructSeries();
}

private void constructSeries() {
    BarChart1.getData().clear();

    for (CheckBox checkBox : checkBoxes) {
        if (checkBox.isSelected()) {
            XYChart.Series series = new XYChart.Series();
            series.setName(checkBox.getText());

            // NOTE : Java SE 7 Code !
            for (Sales sale : sales) {
                if (sale.getVehicle().equals(checkBox.getText())) {
                    series.getData().add(new XYChart.Data<>( sale.getRegion(), sale.getQuantity()));
                }
            }

            BarChart1.getData().add(series);
        }
    }
}

/*
private void constructChoiceBoxes(){}
//Trying to create another choice box in order to choose which date of sales are shown on the graph.
//Need to know where to put the "constructChoiceBox()" and "constructChoiceSeries()" Code for year Choice Boxes.
private void constructChoiceSeries(){}
*/



private static class DashService extends Service<String> {
    private StringProperty address = new SimpleStringProperty();

    public final void setAddress(String address) {
        this.address.set(address);
    }

    public final String getAddress() {
        return address.get();
    }

    public final StringProperty addressProperty() {
       return address;
    }

    @Override
    protected Task<String> createTask() {
        return new Task<String>() {
            private URL url;
            private HttpURLConnection connect;
            private String markup = "";

            @Override
            protected String call() {
                try {
                    url = new URL(getAddress());
                    connect = (HttpURLConnection)url.openConnection();
                    connect.setRequestMethod("GET");
                    connect.setRequestProperty("Accept", "application/json");
                    connect.setRequestProperty("Content-Type", "application/json");                        

                    markup = (new BufferedReader(new InputStreamReader(connect.getInputStream()))).readLine();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    if (connect != null) {
                        connect.disconnect();
                    }
                }

                return markup;
            }
        };
    }
}
}

Gson Java

public class Sales {
final private int Year, QTR, Quantity; 
final private String Region, Vehicle;

public Sales(Integer Year, String Region, Integer QTR, String Vehicle, Integer Quantity) {
    this.Year = Year;
    this.Region = Region;
    this.QTR = QTR;
    this.Vehicle = Vehicle; 
    this.Quantity = Quantity;         
}

@Override
public String toString() {
    return String.format("%s%s%s%s%s", ("Year:" + Year + " "), ("Region:" + Region + " "), ("QTR:" + QTR + " "),("Vehicle:" + Vehicle + " "), ("Quantity:" + Quantity + " "));
}
public Integer getYear() {
    return Year;
}
public String getRegion() {
    return Region;
}
public Integer getQTR() {
    return QTR;
}
public String getVehicle() {
    return Vehicle;
}
public Integer getQuantity() {
    return Quantity;
}
}

0 个答案:

没有答案