Как получить элемент из массива списка объектов - PullRequest
0 голосов
/ 07 декабря 2018

Итак, что мне делать, чтобы "открыть" мой список массивов объектов Встречи?Я пробовал итерацию, но он получает 2 правильных отображения или повторяет последнюю запись.Мне нужно установить текстовые поля для переменной внутри массива объектов.Как мне это сделать?Это календарь, в котором ваши встречи сохраняются в массиве, и выгода состоит в том, что этот список относится к типу объектов, называемых встречами.Я так близок к завершению, что просто не могу понять, что делать с отображением или настройкой информации в текстовых полях.

import java.awt.Color;
import java.util.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;



public class Calendario extends Application {

    private TextField s = new TextField();
    private TextField m = new TextField();
    private TextField t = new TextField();
    private TextField w = new TextField();
    private TextField th = new TextField();
    private TextField f = new TextField();
    private TextField st = new TextField();
    private TextField dom = new TextField();
    private TextField lun = new TextField();
    private TextField mar = new TextField();
    private TextField mie = new TextField();
    private TextField hue = new TextField();
    private TextField vir = new TextField();
    private TextField sab = new TextField();
    private Label firstd = new Label("Sunday");
    private Label secd = new Label("Monday");
    private Label thrd = new Label("Tuesday");
    private Label fortd = new Label("Wednesday");
    private Label fiftd = new Label("Thursday");
    private Label sistd = new Label("Friday");
    private Label svnd = new Label("Saturday");
    private Button submit = new Button();
    private Button open = new Button();
    private Button clear = new Button();
    private ArrayList<Appointment> date = new ArrayList<Appointment>();

public class Appointment{
    DayOfWeek day;
    String tiempo;
    String d;

    Appointment(String tiempo,String d){
        if(Character.isDigit(tiempo.charAt(0)) && tiempo.endsWith("a") || 
                tiempo.endsWith("p")){
        this.tiempo = tiempo;
        }
        else{
            throw new IllegalArgumentException("First input must be numeric and a for am"+
                    "p for pm");
        }
        this.d = d;
    }
}
public void submit(){
    for (DayOfWeek day : DayOfWeek.values()){
        switch (day){
        case SUNDAY: 
           Appointment sunday = new Appointment(s.getText(),dom.getText());
           date.add(sunday);
            break;
        case MONDAY:
            Appointment monday = new Appointment(m.getText(),lun.getText());
            date.add(monday);
            break;
        case TUESDAY:
            Appointment tuesday = new Appointment(t.getText(),mar.getText());
            date.add(tuesday);
            break;
        case WEDNESDAY:
            Appointment wednesday = new Appointment(w.getText(),mie.getText());
            date.add(wednesday);
            break;
        case THURSDAY:
            Appointment thursday = new Appointment(th.getText(),hue.getText());
            date.add(thursday);
            break;
        case FRIDAY:
            Appointment friday = new Appointment(f.getText(),vir.getText());
            date.add(friday);
            break;
        case SATURDAY:
            Appointment saturday = new Appointment(st.getText(),sab.getText());
            date.add(saturday);
            break; 
        default:
            System.out.println("Error oh no help master");
            break;
        }
    }
}

public void open(){


}
public void clear(){
    date.clear();
}

    @Override
    public void start(Stage primaryStage) {
        submit.setText("Submit");
        submit.setStyle("-fx-background-color: #00ff00");
        submit.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
               submit();
            }
        });
        open.setText("Open");
        open.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

                open();
            }
        });
        clear.setText("Clear");
        clear.setStyle("-fx-background-color: #ff0000");
        clear.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                clear();
            }
        });

        HBox frame = new HBox();
        VBox sun = new VBox(10);
        VBox mon = new VBox(10);
        VBox tues = new VBox(10);
        VBox wed = new VBox(10);
        VBox thur = new VBox(10);
        VBox fri = new VBox(10);
        VBox sat = new VBox(10);

        sun.getChildren().addAll(firstd,s,dom);
        mon.getChildren().addAll(secd,m,lun);
        tues.getChildren().addAll(thrd,t,mar);
        wed.getChildren().addAll(fortd,w,mie);
        thur.getChildren().addAll(fiftd,th,hue,clear);
        fri.getChildren().addAll(sistd,f,vir,open);
        sat.getChildren().addAll(svnd,st, sab,submit);

        firstd.setTranslateX(20);
        secd.setTranslateX(20);
        thrd.setTranslateX(20);
        fortd.setTranslateX(10);
        fiftd.setTranslateX(20);
        sistd.setTranslateX(20);
        svnd.setTranslateX(20);

        frame.getChildren().addAll(sun,mon,tues,wed,thur,fri,sat);

        Scene scene = new Scene(frame, 600, 300);

        primaryStage.setTitle("Appoinment Calendar");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

1 Ответ

0 голосов
/ 07 декабря 2018

Код не очень хорошо написан.Просто подумайте, насколько похож код для всех дней.Зачем повторяться, вместо того чтобы придумать подходящую структуру данных, которая позволит вам более удобно получать доступ к объектам?Зачем создавать 2 x 7 TextField s, если вы можете создать 2 и использовать цикл для повторения процесса?

Еще одна вещь, которую вам нужно сделать, - это на самом деле сохранить день недели в вас Appointment.

Реализация open в следующем коде предполагает, что содержимое списка date уже содержит правильные значения, даже если в настоящее время код восстанавливает только последние переданные значения, если пользователь редактирует TextField s..

private ArrayList<Appointment> date = new ArrayList<Appointment>();

public static class Appointment {
    final DayOfWeek day;
    final String tiempo;
    final String d;

    Appointment(String tiempo, String d, DayOfWeek day) {
        if (Character.isDigit(tiempo.charAt(0)) && tiempo.endsWith("a") || tiempo.endsWith("p")) {
            this.tiempo = tiempo;
        } else {
            throw new IllegalArgumentException("First input must be numeric and a for am" + "p for pm");
        }
        this.d = d;
        this.day = day;
    }
}

public void submit() {
    // add appointment for each entry in the map
    inputs.forEach((day, inputs) -> {
        date.add(new Appointment(inputs[0].getText(), inputs[1].getText(), day));
    });
}

public void open() {
    // clear fields
    inputs.values().stream().flatMap(Arrays::stream).forEach(TextField::clear);

    // set text for all elements of date
    date.forEach(appointment -> {
        TextField[] fields = inputs.get(appointment.day);
        fields[0].setText(appointment.tiempo);
        fields[1].setText(appointment.d);
    });
}

public void clear() {
    date.clear();
}

private final Map<DayOfWeek, TextField[]> inputs = new EnumMap<>(DayOfWeek.class);

@Override
public void start(Stage primaryStage) {
    Button submit = new Button("Submit");
    submit.setStyle("-fx-background-color: #00ff00");
    submit.setOnAction(event -> submit());

    Button open = new Button("Open");
    open.setOnAction(event -> open());

    Button clear = new Button("Clear");
    clear.setStyle("-fx-background-color: #ff0000");
    clear.setOnAction(event -> clear());

    GridPane grid = new GridPane();
    grid.setVgap(10);

    Locale locale = Locale.ENGLISH;
    TextStyle textStyle = TextStyle.FULL;
    Insets headerMargin = new Insets(0, 0, 0, 20);

    // add inputs and label for days starting with sunday and store inputs in map
    for (int i = 0; i < 7; i++) {
        DayOfWeek day = DayOfWeek.SUNDAY.plus(i);
        Label label = new Label(day.getDisplayName(textStyle, locale));
        GridPane.setMargin(label, headerMargin);
        TextField timeField = new TextField();
        TextField dField = new TextField();
        inputs.put(day, new TextField[] { timeField, dField });
        grid.addColumn(i, label, timeField, dField);
    }

    HBox buttonContainer = new HBox(10, clear, open, submit);
    buttonContainer.setAlignment(Pos.TOP_RIGHT);
    VBox.setMargin(buttonContainer, new Insets(0, 20, 0, 0));

    VBox root = new VBox(10, grid, buttonContainer);

    Scene scene = new Scene(root, 600, 300);

    primaryStage.setTitle("Appoinment Calendar");
    primaryStage.setScene(scene);
    primaryStage.show();
}
...