Search code examples
arraylistjavafx-8textfield

How to get an item from an array list of objects


So what do I do to "open" my array list of Appointment objects? I have tried iteration but it gets 2 correct displays, or repeats the last entry. I need to set the text fields to a variable inside an array of objects. How do I go about that? This a calendar that saves your appointments into an array list the catch that the list is of an object type called appointments. I am so close to finishing I just can not get what to do with displaying or setting the information into the text fields.

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);
    }

Solution

  • The code is not well written. Just consider how similar the code for all the days is. Why repeat yourself instead of coming up with a suitable data structure that allows you to access the objects more conveniently? Why create 2 x 7 TextFields when you can create 2 and use a loop to repeat the process?

    One more thing you need to do is actually store the day of the week in you Appointment.

    The open implementation in the following code assumes the content of the date list already contains the proper values even though currently the code only restores the last submitted values, if the user edits the TextFields.

    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();
    }