Question

I have just registered because I have to present a JavaFX app tomorrow morning 24th february and after trying lots of things I haven't been able to get a solution for the final part of my app.

The app I am developing is a game where the user is one player, the PC is the other player and the "machine" is the entity who generates a random number.

If they guess the numbers that are coming, they are adding points to its score.

At the end, the first one (user or PC) who reaches the 10 points wins the game.

Everything is coded until here, but when I try to end the game showing the message of the winner and exiting the game, I am not able to find the code that I have to write to quit the game and close the window 10 seconds after the message with the winner of the game is shown in the text area.

Could you help me telling me the code I have to put on my app to close it automatically 10 seconds after the winner's message comes up, please???

I need it for tomorrow 24th february at 07:30 GMT time.

I attached the 4 files that I have: the main code of my JavaFX app, a CSS for the styles, a FXML file for the graphical interface and elements and a Java file that is used to launch the app (I think). The app is called "Ramdoning". I am from Spain, so some words and comments are in Spanish. Just go to the zone with ///////////////////////////////////. There is where I want to know what do I have to place.

Could you also tell me what do I have to do to have one number predetermined in the combobox of the .fxml file, please??? To show the number 5 since the start of the program, for instance.

Here they are (the files):

Estilos.css:

.fondo {
    -fx-background-color: #0B610B;
}

.titulo {
    -fx-font-family: Arial;
    -fx-font-weight: Bold;
    -fx-font-size: 30px;
    -fx-text-align: centre;
    -fx-text-fill: #66BBFC;
}

.texto {
    -fx-font-family: Arial;
    -fx-font-weight: Bold;
    -fx-font-size: 15px;
    -fx-text-fill: #F49A09;   
}

FXMLDocument.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?> 
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="700.0" prefWidth="600.0" styleClass="fondo"                                                                  xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="ramdoning.FXMLDocumentController">                
<children>
    <Label fx:id="label" layoutX="126.0" layoutY="120.0" minHeight="16.0" minWidth="69.0" />
    <Label layoutX="218.0" layoutY="38.0" styleClass="titulo" text="Ramdoning" visible="true">
  <stylesheets>
    <URL value="@Estilos.css" />
  </stylesheets>
</Label>
<Label layoutX="44.0" layoutY="104.0" styleClass="texto" text="¿Que número aleatorio del 1 al 10 crees que la maquina va a generar?">
  <stylesheets>
    <URL value="@Estilos.css" />
  </stylesheets>
</Label>
<TextField fx:id="tfAleatuser" layoutX="44.0" layoutY="136.0" prefWidth="200.0" text="1" />
<Label layoutX="44.0" layoutY="190.0" styleClass="texto" text="¿Qué número del 1 al 10 crees que va a elegir el PC?">
  <stylesheets>
    <URL value="@Estilos.css" />
  </stylesheets>
</Label>
<ComboBox id="cb" fx:id="cbAleatpc" disable="false" layoutX="44.0" layoutY="223.0" visibleRowCount="10">
  <items>
    <FXCollections fx:factory="observableArrayList">
      <String fx:value="1" />
      <String fx:value="2" />
      <String fx:value="3" />
      <String fx:value="4" />
      <String fx:value="5" />
      <String fx:value="6" />
      <String fx:value="7" />
      <String fx:value="8" />
      <String fx:value="9" />
      <String fx:value="10" />
    </FXCollections>
  </items>
</ComboBox>
<Button fx:id="btAjugar" layoutX="437.0" layoutY="136.0" mnemonicParsing="false" onAction="#aJugar" prefHeight="54.0" prefWidth="117.0" text="¡A jugar!" />
<Label layoutX="44.0" layoutY="278.0" styleClass="texto" text="Resultado:">
  <stylesheets>
    <URL value="@Estilos.css" />
  </stylesheets>
</Label>
<TextArea fx:id="taResultado" editable="true" layoutX="44.0" layoutY="307.0" opacity="0.72" prefHeight="355.0" prefWidth="510.0" wrapText="true" />
</children>
<stylesheets>
<URL value="@Estilos.css" />
</stylesheets>
</AnchorPane>

Ramdoning.java:

package ramdoning;

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

public class Ramdoning extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);

    stage.setScene(scene);
    stage.show();
}

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

}

FXMLDocumentController.java (Here is where I think I have to do the modifications. See the /////////////////):

package ramdoning;

import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class FXMLDocumentController implements Initializable {

// Declaramos las variables que vamos a utilizar para extraer la información del    usuario:
@FXML private TextField tfAleatuser;    
@FXML private ComboBox cbAleatpc;
@FXML private TextArea taResultado;

// Inicializamos los contadores necesarios para establecer el marcador: 
int puntosusuario = 0;
int puntospc = 0;

// Establecemos las instrucciones a seguir a la hora de pulsar el botón establecido para jugar:
@FXML
private void aJugar(ActionEvent event) {

    // Pasamos a cadenas la información introucida por el usuario en la interfaz gráfica:

    // El número aleatorio que el usuario cree que la máquina va a generar:
    String au = tfAleatuser.getText();

    // El número aleatorio que el usuario cree que el PC ha elegido:
    String auc = cbAleatpc.getValue().toString();       

    // Comenzamos a generar aleatoriamente los números del PC y de la máquina:
    Random rnd = new Random();

    // Generamos el número aleatorio de la máquina y lo pasamos a una cadena:
    int aleatorio = rnd.nextInt(10)+1;        
    String ag = Integer.toString(aleatorio);

    // Generamos (de forma aleatoria) el número que el PC cree que va a sacar la máquina y lo pasamos a una cadena: 
    int aleatorio_pc = rnd.nextInt(10)+1;
    String ac = Integer.toString(aleatorio_pc);

    // Generamos (de forma aleatoria) el número que el PC cree que el usuario ha elegido y lo pasamos a una cadena: 
    int aleatorio_pc_u = rnd.nextInt(10)+1;
    String acu = Integer.toString(aleatorio_pc_u);

    // Mostramos los primeros datos en la caja de los resultados:
    taResultado.setText("Nº aleatorio elegido por el usuario: "+au+"\n\n");
    taResultado.appendText("Nº aleatorio elegido por el PC: "+ac+"\n\n");
    taResultado.appendText("El nº que el usuario piensa que el PC ha elegido es: "+auc+"\n\n");
    taResultado.appendText("El nº que el PC piensa que el usuario ha elegido es: "+acu+"\n\n");
    taResultado.appendText("Nº aleatorio generado: "+ag+"\n\n");

    // Realizamos las comparaciones necesarias para determinar cuántos puntos ha ganado cada uno y vamos añadiendo información a la caja de resultados:
    if(au.equals(ag))
    {
        puntosusuario++;
        taResultado.appendText("¡¡¡El usuario ha adivinado el número aleatorio generado por la máquina!!!\n\n");
    }

    if(auc.equals(ac))
    {
        puntosusuario++;
        taResultado.appendText("¡¡¡El usuario ha adivinado el número elegido por el PC!!!\n\n");
    }

    if(ac.equals(ag))
    {
        puntospc++;
        taResultado.appendText("¡¡¡El PC ha adivinado el número aleatorio generado por la máquina!!!\n\n");
    }

    if(acu.equals(au))
    {
        puntospc++;
        taResultado.appendText("¡¡¡El PC ha adivinado el número elegido por el usuario!!!\n\n");
    }

    // Pasamos a cadenas los puntos de ambos para mostrar el marcador actual:
    String puntosu = Integer.toString(puntosusuario);
    String puntosc = Integer.toString(puntospc);       

    taResultado.appendText("Marcador:\n"
        + "Usuario: "+puntosu+"\n"
        + "Ordenador: "+puntosc+"\n\n");

    // Cuando uno de los 2 llega a 10 y gana lo mostramos y cerramos el programa tras 5 segundos:
    if(puntosusuario == 10)
    {
        taResultado.appendText("¡¡¡El usuario gana la partida!!!");
        /////////////////////////////////////////
    }           

    if(puntospc == 10)
    {
        taResultado.appendText("¡¡¡El PC gana la partida!!!");
        /////////////////////////////////////////
    }       
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}    

}

No correct solution

OTHER TIPS

You can use System.exit(...) to exit and a plain old Java Timer to schedule it for 10 seconds in the future. The code is pretty minimal:

new Timer().schedule(new TimerTask() {
    public void run () { System.exit(0); }
}, 10000); 
// now show message.

Using System.exit() to exit the application can cause a lot of problems. To name a few - this will cause all finally blocks to be skipped. Use Platform.exit() instead for nice and clean exit.

You should use Platform.exit() to exit JavaFX application, and a plain old Java Timer to schedule it for 10 seconds in the future. The code is pretty minimal:

new Timer().schedule(new TimerTask() {
    public void run () { Platform.exit(); }
}, 10000); 
// now show message.

The advantage of Platform.exit() over System.exit() is that it fires Application.stop() method before exiting where you can destroy resources properly.

To terminate the execution of any Java application:

System.exit(0);

The 0 may be substituted with any applicable status code.

To delay this, you could add it to a timer, or thread it with a delay.

Here is an example of threading.

new Thread(){
    public void run(){
        try{
            Thread.sleep(5000);
        }catch(Exception e){
        }finally{
            System.exit(0);
        }
    }
}.start();

*Code from memory, may need minor adjustments to compile.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top