一旦用户输入了车辆名称和ID,然后点击添加车辆,就可以创建一个车辆对象并将其存储在车辆数组列表中。
如何将来自GUI的输入数据存储到arraylist中?
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
GridPane gridPane = new GridPane();
Label VehicleName = new Label("Vehicle Name ");
TextField VehicleNameF = new TextField();
Label Vehicle_ID = new Label("Vehicle ID");
TextField VehicleID = new TextField();
Button AddButton = new Button("Add Vehicle");
gridPane.setHgap(15);
gridPane.setVgap(15);
gridPane.add(VehicleName, 0, 0);
gridPane.add(Vehicle_ID, 0, 1);
gridPane.add(VehicleNameF, 1, 0);
gridPane.add(VehicleID, 1, 1);
gridPane.add(AddButton, 1, 2, 2, 1);
Scene scene = new Scene(gridPane, 300, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
}
答案 0 :(得分:0)
首先,您必须创建:
class Vehicle {
long vehicleId;
String vehicleName;
Vehicle(){
}
void setVehicleId(long vehicleID){
this.vehicleId=vehicleID;
}
long getVehicleId(){
return vehicleId;
}
void setVehicleName(vehicleName){
this.vehicleName=vehicleName;
}
String getVehicleName(){
return vehicleName;
}
}
下一步,您必须创建新的对象:
Vehicle vehicle1=new Vehicle();
要添加指定值的地方
vehicle1.setVehicleName(Vehicle name-variable got from swing);
vehicle1.setVehicleId(Vehicle id-variable got from swing);
列表:
List<Vehicle> vehiclesList=new ArrayList<Vehicle>()
vehiclesList.add(vehicle1);
答案 1 :(得分:0)
您缺少以下内容:
AddButton.setOnAction(e ->
{
vehicle1.setVehicleId(VehicleID.getText());
vehicle1.setVehicleName(VehicleNameF.getText());
});
答案 2 :(得分:0)
首先,为您的对象创建一个数组:车辆。
要从GUI获取数据,您需要事件监听器:
AddButton.setOnAction(e ->
{
Vehicule vehicule = new Vehicule();
vehicle.setVehicleId(VehicleID.getText());
vehicle.setVehicleName(VehicleNameF.getText());
Vehicules.add(vehicule);
//Vehicules is the array where you put all your objects.
})
这能回答您的问题吗?