Poderia uma etiqueta ser modificado por outro método dentro de uma classe estendida?

Arduino Mandarelli:

Eu estou tentando criar um sistema de reservas Cinema que permite que o usuário para comprar bilhetes e lanches, e a cada clique atualizar a etiqueta.

Eu tenho duas classes:

public class DashboardUserController{

  public Label subtotal;
  public static Double subtotalCounter = 0.0;
  public static Double filmPrice;

  @FXML
  public void onWaterBottleClick(){
    subtotalCounter = subtotalCounter + 1.50;
    orderRecipt = orderRecipt + "Water Bottle 1.50£ \n";
    setSubtotal();
  }
  // and similar methods for each type of snack 

public void setSubtotal(){
    subtotal.setText(subtotalCounter.toString() + " £");
  }

// set the price for each click on the label

  public void addTicket() {
    System.out.println(subtotalCounter);
    subtotalCounter = subtotalCounter + filmPrice;
    setSubtotal();
  } 
}

E outra classe que estende a DashboardUserController

public class TheatresController extends DashboardUserController {

  @FXML
  private void onClick(MouseEvent event) {                  //method for selection/deselection of seats
    ImageView imageView = (ImageView) event.getSource();
    if (imageView.getImage() == redSeat) {
      Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Do you want to proceed with the unbooking?", ButtonType.YES, ButtonType.NO);
      if (alert.showAndWait().orElse(ButtonType.NO) == ButtonType.YES) {
        imageView.setImage(imageView.getImage() == redSeat ? greenSeat : redSeat);
      }
    } else {
      Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Do you want to proceed with the booking?", ButtonType.YES, ButtonType.NO);
      if (alert.showAndWait().orElse(ButtonType.NO) == ButtonType.YES) {
        imageView.setImage(imageView.getImage() == redSeat ? greenSeat : redSeat);
        addTicket();
      }
    }
  }

Agora se eu clicar nos botões de alimentos a subtotalCounter ea etiqueta corretamente atualizados: Observe a etiqueta inferior direito "subtotal"

Console Valor

Mas quando eu clico os assentos, o preço do filme foi correctamente adicionado mas o rótulo tornou-se "null" e me dar uma NullPointerException.

O estranho é que se eu clicar novamente qualquer lanche a exibição rótulo corretamente o preço dos alimentos selecionados mais o preço do filme para cada assento selecionado.

digite descrição da imagem aqui digite descrição da imagem aqui

digite descrição da imagem aqui

Firstly I thought that the problem was on the nullPointException so I checked this question. Then I tried to understand if an extended class as thiscan call a Label and modify it, the answer seem yes but for an awful reason doesn't seem apply to my scenario.

Thanks to everybody.

Matt :

So there is a lot wrong(Exaggeration for effect) but you are learning so I will do my best to help. Please read it all before copying and pasting into your program so you understand it

Starting off the reason you were getting a null pointer was due to the fact that you had extend DashBoardUserController which means that the DashBoardUserController that the program was initialized with was not talking to your TheatresController and when you tried to access it it gave you a null pointer because nothing was initialized in the extended class

So Step 1 remove the extend DashBoardUserController

So since that is gone we need to get a reference of DashBoardUserController to that class so that it can call the necessary methods we can do that on initialization of TheatresController like so

        FXMLLoader loader = new FXMLLoader(getClass().getResource(resourceLocation));
        Pane pane = loader.load();
        TheatresController controller = loader.getController();
        controller.setDashBoardUserControllerReference(this);//We'll get here

Next is to make necessary methods and variables in TheatresController

private DashboardUserController dashboardUserController;//Set at top of class

public void setDashBoardUserControllerReference(DashboardUserController dashboardUserController){
    this.dashboardUserController = dashboardUserController;
}

Done this will fix the null pointer moving on to generify your method because there is a lot of code replication which for you is unnecessary typing

@FXML
public void onjosephclick() {
    //weekPickerInput();                                //You can delete from here
    //addFilmsInList();
    //filmList.setShowLocation("Joseph P");
    //System.out.println("joseph button pressed");
    //try {
    //    Pane pane = FXMLLoader.load(getClass().getResource("scenes/josephpane.fxml"));
    //    seatsSelection.getChildren().setAll(pane);
    //} catch (IOException e) {
    //    System.out.println(e);
    //}
    //setStuff();
    //seatsavailable.setText(Integer.toString(seatsJoseph));
    //filmPrice = filmList.searchFilm().get().getPrice();
    //System.out.println("Price:"+filmPrice);            //Down to here
    genericOnClick("Joseph P","scenes/josephpane.fxml",seatsJoseph);
    //change the strings for each call and remove the unnecessary stuff 
    //in the methods it will clean it up a lot
}

private void genericOnClick(String location, String resourceLocation, int seats) {
    weekPickerInput();
    addFilmsInList();
    filmList.setShowLocation(location);
    System.out.println("Location:"+location);
    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource(resourceLocation));
        Pane pane = loader.load();
        TheatresController controller = loader.getController();
        controller.setDashBoardUserControllerReference(this);
        seatsSelection.getChildren().setAll(pane);
    } catch (IOException e) {
        System.out.println(e);
    }
    setStuff();
    seatsavailable.setText(Integer.toString(seats));
    filmPrice = filmList.searchFilm().get().getPrice();
    System.out.println("Price:"+filmPrice);
}

Algumas outras coisas aprender a aprender, eventualmente, são convenções de nomenclatura Java, lidar com a replicação de código que eu vi uma boa quantidade de código que pode ser generified como eu mostrei no método acima

Bom código sorte em bom senhor. Se não o seu trabalho eu posso postar a classe completo, mas eu acho que você deve tentar e figura-lo como a sua boa prática e eu dei-lhe todo o código que você precisa deixe-me saber se você precisar de mais ajuda

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=214830&siteId=1
Recomendado
Clasificación