Can I use a text value to selectToggle()? - javafx

I am using a text file to load information to a javafx gui. Is there a way I can use a text value there to select a radio button in a toggle group.
I think '''toggleGroup.selectedValue(toggle value)''' is the function I need, but it does not take a string. Is there a way to convert the string to a toggle value, indirectly?
The following does not work because '''selectToggle()''' takes a toggle not a text value and neither an implicit nor explicit '''(toggle)''' cast seem to work.
tgrpSex.selectToggle(read.nextLine());
This should be reproducible:
package programmingassignment1;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
//import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class Address extends Application {
RadioButton rbMale = new RadioButton("Male");
RadioButton rbFemale = new RadioButton("Female");
ToggleGroup tgrpSex = new ToggleGroup();
GridPane rootPane = new GridPane();
#Override
public void start(Stage primaryStage){
//Setting an action for the Open Contact button
Button btOpenContact = new Button("Open Contact");
File file = new File("AddressBook.txt");
btOpenContact.setOnAction(event -> {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
});
//Setting an action for the Save button
Button btSave = new Button("Save");
btSave.setOnAction(
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{saveContact(file);}
catch(Exception f){f.getMessage();}
}});
//associate radio buttons with a toggle group
rbMale.setToggleGroup(tgrpSex);
rbFemale.setToggleGroup(tgrpSex);
rbMale.setOnAction(e -> {
if(rbMale.isSelected()){int maleContact = 1;}
});
rbFemale.setOnAction(e -> {
if(rbFemale.isSelected()){int maleContact = 0;}
});
rootPane.add(new Label("Sex"), 3, 1);
rootPane.add(rbFemale, 3, 2);
rootPane.add(rbMale, 3, 3);
rootPane.add(btOpenContact, 1, 13);
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
//this code might cause a FileNotFoundException
//if it does it creates an exception object of the above type
try{
//PrintWriter output = new PrintWriter (file);
PrintStream output = new PrintStream(file);
output.println(tfContactFirst.getText());
output.println(tfContactLast.getText());
output.println(tfSpouseFirst.getText());
output.println(tfSpouseLast.getText());
output.println(cboWorkHome.getValue());
output.println(tfStreet.getText());
output.println(tfCity.getText());
output.println(tfState.getText());
output.println(tfZip.getText());
output.close();
}
//what do do with exception
//here the catch clause with create another exception
//that is passed the result of the getMessage() method from the original exception
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
//read same text file you save too
public void openContact(File file) throws FileNotFoundException, Exception{
try{
Scanner read = new Scanner(file);
while(read.hasNextLine()){
//how do I save the imageFileName
tfContactFirst.setText(read.nextLine());
tfContactLast.setText(read.nextLine());
tgrpSex.selectToggle(read.nextLine());
tfSpouseFirst.setText(read.nextLine());
tfSpouseLast.setText(read.nextLine());
//tfSpouseGender.setText(read.nextLine());
cboWorkHome.setValue(read.nextLine());
tfStreet.setText(read.nextLine());
tfCity.setText(read.nextLine());
tfState.setText(read.nextLine());
tfZip.setText(read.nextLine());
//taNotes.setText(read.nextLine());
}
}
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
}
No results <- syntax error

Sorry. I got the answer. I didn't know what a toggle type object was. I looked up an examples of selectToggle() and learned you can pass a radio button object to it. So I put that in an if then statement. if(read.nextLine().equals("Male")){tgrpSex.selectToggle(rbMale);}
else{tgrpSex.selectToggle(rbFemale);}

Related

How to pass file path from a FileChooser button to another button?

I'm trying to make a program with some filters of image by using JavaFx, so I need two button at least, one is a file chooser to open an image, and another one will be a choice box that allows to choose a filter.
My problem is how could a choice box get the path name or a file object from the file chooser.
here is my program unfinished :
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Filter extends Application{
public void start(final Stage stage) {
stage.setTitle("FilterShop");
final FileChooser fileChooser = new FileChooser();
final Button openButton = new Button("Select a photo");
ChoiceBox<String> choiceBox = new ChoiceBox<>();
choiceBox.getItems().add("Choose a Filter");
choiceBox.getItems().addAll("Remove watermark", "Brightness", "Grey", "Mosaic");
choiceBox.getSelectionModel().selectFirst();
final Pane stac = new Pane();
openButton.setOnAction(e -> {
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
Image image = new Image(file.toURI().toString());
ImageView imageView = new ImageView(image);
imageView.setX(50);
imageView.setY(50);
imageView.setFitWidth(300);
imageView.setFitHeight(470);
imageView.setPreserveRatio(true);
stac.getChildren().add(imageView);
}
});
choiceBox.setOnAction(event1 -> {
if (choiceBox.getValue() == "Mosaic") {
try {
BufferedImage imagen = ImageIO.read(/* A file object is needed here. */ );
new Mosaic().mosaico(imagen, 80, 80);
} catch (IOException ie) {
System.err.println("I/O Error");
ie.printStackTrace(System.err);
}
}
});
openButton.setLayoutX(300);
openButton.setLayoutY(350);
choiceBox.setLayoutX(430);
choiceBox.setLayoutY(350);
stac.getChildren().addAll(openButton, choiceBox);
stage.setScene(new Scene(stac, 800, 400));
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
I am not sure what is the exact issue you are facing. Firstly FileChooser is not a Button. It is a helper class to interact with ToolKit to open the OS specific file chooser and return the results. And obvisously, it will no keep record of the returned results.
It is your duty to keep a reference of the retrieved file. This can be done in "N" number of ways. As you question focuses on get getting the value from the open button, I would suggest the below approach.
openButton.setOnAction(e -> {
File file = fileChooser.showOpenDialog(stage);
openButton.getProperties().put("FILE_LOCATION", file.getAbsolutePath());
...
});
choiceBox.setOnAction(event1 -> {
if (choiceBox.getValue() == "Mosaic") {
File file = new File(openButton.getProperties().get("FILE_LOCATION").toString());
}
});

Alert in JAVA FX

I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Yes/No from the UI .
Code:
This is how the controller is coded.
package application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class WarningController implements Initializable {
#FXML
public Button yes;
#FXML
public Button no;
public static String type;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public String confirmSelection(ActionEvent event)throws IOException{
Button button = (Button) event.getSource();
type = button.getText();
if(type.equals("Yes")){
Stage stage = (Stage) yes.getScene().getWindow();
stage.close();
//System.out.println("Yes");
return type;
}
else{
//System.out.println("No");
Stage stage1 = (Stage) no.getScene().getWindow();
stage1.close();
return type;
}
}
/********************************************************************************/
public void writesheet(String[][] result,String ComboValue,String[] heading) throws IOException{
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
//Create row object
XSSFRow row;
String[][] towrite=result;
int rows=towrite.length;
//int cols=towrite[0].length;
// System.out.println(rows +" "+ cols);
Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
empinfo.put("0", heading);
for(int i=1;i<=rows;i++){
empinfo.put( Integer.toString(i),towrite[i-1]);
}
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid)
{
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr)
{
Cell cell = row.createCell(cellid++);
//cell.setCellValue((String)obj);
cell.setCellValue(obj.toString());
}
}
//Write the workbook in file system
File f=new File(("C:\\"+ComboValue+".xlsx"));
if(f.exists()){
Stage primaryStage=new Stage();
Parent root=FXMLLoader.load(getClass().getResource("/application/Warning.fxml"));
Scene scene = new Scene(root,350,150);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(type);
}
FileOutputStream out = new FileOutputStream(f);
workbook.write(out);
out.close();
System.out.println(ComboValue+" "+"Excel document written successfully" );
workbook.close();
}
}
I want to use button value(stored in String type) in writesheet function. Now it is returning NULL.
Please suggest if there is any other way to show warning.I am using two fxml files and this is the second excel file.
[1]: http://i.stack.imgur.com/ZK6UC.jpg
Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.
Alert alert = new Alert(AlertType.WARNING,
"File already exists. Do you want to override?",
ButtonType.YES, ButtonType.NO);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
Also here is a good tutorial.
I usually make a method, and call it if certain conditions are not met.
Ex:
if(condition)
alert();
public void alert(){ //alert box
Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO); //new alert object
alert.setTitle("Warning!"); //warning box title
alert.setHeaderText("WARNING!!!");// Header
alert.setContentText("File already exists. Overwrite?"); //Discription of warning
alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
}
I grabbed some code from Jhonny007, credit to him.

Why my Stage.close is not Working

Stage.close() is not working for me.
I've checked on:
JavaFX 2.0: Closing a stage (window)
Here is my codes:
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.stage.Modality;
public class MsgBox {
public Stage MessageBox(String Title, String Message){
VBox Pnl = new VBox();
Pnl.setPadding(new Insets(10,10,10,10));
Pnl.setSpacing(10);
Pnl.setAlignment(Pos.CENTER);
Label LblMsg = new Label(Message);
Button CmdOK = new Button("OK");
Pnl.getChildren().addAll(LblMsg, CmdOK);
Scene SCN = new Scene(Pnl);
Stage Window = new Stage();
Window.initModality(Modality.APPLICATION_MODAL);
Window.setTitle(Title);
Window.setScene(SCN);
Window.showAndWait();
CmdOK.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent ev){
Window.close();
}
});
return Window;
}
}
Here is the code that calls the Message Box Class:
CmdUpdate.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent ev){
new MsgBox().MessageBox("Hello", "Hello World");
}
});
Calling Stage#showAndWait waits until the stage closes before returning, so in fact the next line never gets a chance to run.
Move the line
Window.showAndWait();
to be the last in the method (crucially - after you set the handler to allow closing the stage), or else just use Stage#show, and your problem should be solved.

JavaFX, text won't display in TextArea

I have the majority of the program done, the only problem is getting the numbers to display in the TextArea. Write a program that lets the user enter numbers from a graphical user interface and displays them in a text area. Use a LinkedList to store the numbers. Don't duplicate numbers. Add sort, shuffle, reverse to sort the list.
package storedInLinkedList;
import java.util.Collections;
import java.util.LinkedList;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.ScrollPane;
public class StoredInLinkedList extends Application{
TextField txt = new TextField();
TextArea tArea = new TextArea();
Label message = new Label("Enter a Number: ");
Button sort = new Button("Sort");
Button shuffle = new Button("Shuffle");
Button reverse = new Button("Reverse");
private LinkedList<Integer> list = new LinkedList<>();
#Override
public void start(Stage primaryStage){
BorderPane bPane = new BorderPane();
txt.setAlignment(Pos.TOP_RIGHT);
bPane.setCenter(txt);
bPane.setBottom(tArea);
HBox hBox = new HBox(message, txt);
bPane.setTop(hBox);
HBox buttons = new HBox(10);
buttons.getChildren().addAll(sort, shuffle, reverse);
bPane.setBottom(buttons);
buttons.setAlignment(Pos.CENTER);
VBox vBox = new VBox();
vBox.getChildren().addAll(hBox, tArea, buttons);
bPane.setCenter(new ScrollPane(tArea));
Scene scene = new Scene(vBox, 300,250);
primaryStage.setTitle("20.2_DSemmes");
primaryStage.setScene(scene);
primaryStage.show();
txt.setOnAction(e -> {
if(! list.contains(new Integer(txt.getText()))){
tArea.appendText(txt.getText() + " ");
list.add(new Integer(txt.getText()));
}//end if
});//end action
sort.setOnAction(e -> {
Collections.sort(list);
display();
});//end action
shuffle.setOnAction(e -> {
Collections.shuffle(list);
display();
});//end action
reverse.setOnAction(e -> {
Collections.reverse(list);
display();
});//end action
}//end stage
private void display() {
for (Integer i: list){
tArea.setText(null);
tArea.appendText(i + " ");
}//end for
}//end display
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}//end main
}//end class
Put the textarea clearing code outside of for loop. Otherwise you are clearing the previously appended text, so textarea having only the last element of list:
private void display() {
tArea.setText(""); // clear text area
for (Integer i: list){
tArea.appendText(i + " ");
}//end for
}/

Refresh label in JAVAFX

So i have this code in which i'm trying to do a scene for my game. I'm really a beginner in a Java and especially JAVAFX world and doing this as a school project (Once again..) and trying to figure out a way to refresh my label.
I've found one URL from stackoverflow, which was a similar issue but didn't work for my problem (or was i too stupid to make it work..) anyways, link is here
This is the part where the problem occurs - i have a text box, from which you have to enter player names. Every time a user inputs player name the label shows how many names have been entered, according to the nimedlist.size() which holds the names inside.
Label mängijate_arv = new Label("Mängijaid on sisestatud: "+nimedlist.size());
// if we press enter, program will read the name
nimiTekst.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(final KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
if (nimiTekst.getText() != null) {
nimedlist.add(nimiTekst.getText());
nimiTekst.setText(null);
}
}
}
});
startBox.getChildren().addAll(sisestus_mängijad, nimiTekst, mängijate_arv,
startButton2);
This is the whole code:
package application;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Baila2 extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(final Stage peaLava) {
final Group root = new Group();
final BorderPane piir = new BorderPane();
piir.setPrefSize(960, 540);
final Text tekst = new Text();
tekst.setText("JOOMISMÄNG");
tekst.setFont(Font.font("Verdana", 40));
VBox nupudAlam = new VBox();
Button startButton = new Button("Start");
nupudAlam.setSpacing(20);
Button reeglidButton = new Button("Reeglid");
nupudAlam.setAlignment(Pos.CENTER);
startButton.setId("btn3");
startButton.setMaxWidth(160);
reeglidButton.setMaxWidth(160);
reeglidButton.setId("btn3");
nupudAlam.getChildren().addAll(startButton, reeglidButton);
piir.setTop(tekst);
piir.setAlignment(tekst, Pos.CENTER);
piir.setCenter(nupudAlam);
root.getChildren().add(piir);
// START NUPP TÖÖ
startButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(final ActionEvent event) {
final ArrayList nimedlist = new ArrayList();
piir.setVisible(false);
final BorderPane startPiir = new BorderPane();
final VBox startBox = new VBox();
Button startButton2 = new Button("ALUSTA!");
startButton2.setId("btn2");
startButton2.setMaxWidth(160);
startPiir.setPrefSize(960, 540);
final Text startTekst = new Text();
startTekst.setText("JOOMISMÄNG");
startTekst.setFont(Font.font("Verdana", 40));
startPiir.setTop(startTekst);
startPiir.setAlignment(startTekst, Pos.CENTER);
final TextField nimiTekst = new TextField();
nimiTekst.setText(null);
nimiTekst.setMaxWidth(250);
Label sisestus_mängijad = new Label(
"Sisesta 3-9 mängija nimed:");
sisestus_mängijad.setFont(Font.font("Verdana", 30));
sisestus_mängijad.setTextFill(Color.ORANGE);
Label mängijate_arv = new Label("Mängijaid on sisestatud: "+nimedlist.size());
// kui vajutatakse ENTER,siis loeme nime
nimiTekst.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(final KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
if (nimiTekst.getText() != null) {
nimedlist.add(nimiTekst.getText());
nimiTekst.setText(null);
}
}
}
});
startBox.getChildren().addAll(sisestus_mängijad, nimiTekst, mängijate_arv,
startButton2);
startBox.setSpacing(20);
startBox.setAlignment(Pos.CENTER);
startPiir.setCenter(startBox);
root.getChildren().add(startPiir);
}
});
// aknasündmuse lisamine
peaLava.setOnHiding(new EventHandler<WindowEvent>() {
public void handle(WindowEvent event) {
// luuakse teine lava
final Stage kusimus = new Stage();
// küsimuse ja kahe nupu loomine
Label label = new Label("Kas tõesti tahad kinni panna?");
Button okButton = new Button("Jah");
Button cancelButton = new Button("Ei");
// sündmuse lisamine nupule Jah
okButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
kusimus.hide();
}
});
// sündmuse lisamine nupule Ei
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
peaLava.show();
kusimus.hide();
}
});
// nuppude grupeerimine
FlowPane pane = new FlowPane(10, 10);
pane.setAlignment(Pos.CENTER);
pane.getChildren().addAll(okButton, cancelButton);
// küsimuse ja nuppude gruppi paigutamine
VBox vBox = new VBox(10);
vBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(label, pane);
// stseeni loomine ja näitamine
Scene stseen2 = new Scene(vBox);
kusimus.setScene(stseen2);
kusimus.show();
}
}); // siin lõpeb aknasündmuse kirjeldus
// stseeni loomine ja näitamine
Scene stseen1 = new Scene(root, 960, 540, Color.GREEN);
peaLava.setTitle("BAILA 2.0");
// peaLava.setResizable(false);
stseen1.getStylesheets().add(
getClass().getClassLoader().getResource("test.css")
.toExternalForm());
peaLava.setScene(stseen1);
peaLava.show();
}
}
Sorry about Estonian language, it's compulsory in our school to write in our native language..
You can just do
nimiTekst.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(final KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
if (nimiTekst.getText() != null) {
nimedlist.add(nimiTekst.getText());
nimiTekst.setText(null);
mängijate_arv.setText("Mängijaid on sisestatud: "+nimedlist.size());
}
}
}
});
If you are not using Java 8 (you appear not to be, since you are implementing all the handlers the old, long way...), you will have to declare mängijate_arv as final:
final Label mängijate_arv = new Label("Mängijaid on sisestatud: "+nimedlist.size());
If you want to be extra cool with this, you can use bindings instead. You will have to make nimidlist an observable list:
final ObservableList<String> nimedlist = FXCollections.observableArrayList();
and then:
mängijate_arv.bind(Bindings.format("Mängijaid on sisestatud: %d", Bindings.size(nimedList)));
and don't put the mängijate_arv.setText(...) call in the handler. This solution is nicer in many ways, as if you remove items from the list (or add other items elsewhere in your code), then the label will still remain properly updated without any additional code.
One other thing: it's a bit better to use an action handler on the text field, instead of a low-level key event handler:
nimiTekst.setOnAction(new EventHandler<ActionEvent>() {
public void handle(final ActionEvent keyEvent) {
if (nimiTekst.getText() != null) {
nimedlist.add(nimiTekst.getText());
nimiTekst.setText(null);
mängijate_arv.setText("Mängijaid on sisestatud: "+nimedlist.size());
}
}
});
(Sorry if I mangled your variable names. My Estonian is a bit weak ;). Your school's policy is a good one, for what it's worth.)

Resources