Felhasználói eszközök

Eszközök a webhelyen


oktatas:programozas:java:java_fx:tananyag

< Java FX

Java FX tananyag

Helló Világ

Első programunk egy ablakot jelenít meg egy felirattal. Ehhez négy osztályra van szükségünk.

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
 
public class App extends Application {
    @Override
    public void start(Stage stage) {
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Helló Világ!");
        stage.show();
    }
}

A stage egy ablaknak felel meg. A scene azon belül egy konténernek.

Futtatás a bin könyvtárból:

java --module-path /home/janos/Library/javafx-sdk-16/lib --add-modules javafx.controls,javafx.fxml App

A main() metódus

A JavaFX program elfut a main() metódus nélkül is; azért szokták hozzáadni, mert így kezelhetők a parancssori argumentumok is.

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
 
public class App extends Application {
    @Override
    public void start(Stage stage) {
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Helló Világ!");
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

Egyes kódszerkesztők (ilyen a Visual Studio Code is) esetén előfordulhat, hogy nem hajlandó futni csak main() metódus megléte esetén.

Text

A Text osztály szöveg megjelenítésére alkalmas.

App.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws Exception {
        Text text = new Text("Helló");
        Scene scene = new Scene(new VBox(text), 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
}

Szöveg elhelyezése

App.java
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) throws Exception {
        Text text = new Text();
        text.setText("Helló Világ");
        text.setX(150);
        text.setY(150);
        Group root = new Group(text);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
}

Label

A Label osztály szöveg és mellette egy kép megjelenítésére alkalmas.

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
 
public class App extends Application {
    @Override
    public void start(Stage stage) {
        Label label = new Label("Helló");
        Scene scene = new Scene(label, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

Fontbeállítás:

import javafx.scene.text.Font;
 
...
 
label.setFont(new Font("Arial", 24));

Szövegbeállítás:

label.setText("Új szöveg");

Kép beállítása szöveg mellé:

...
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
 
...
 
String iconPath = "resources/images/icon01.png";
FileInputStream input = new FileInputStream(iconPath);
Image image = new Image(input);
ImageView imageView = new ImageView(image);
Label label = new Label("Helló", imageView);

A fájlbeolvasást tegyük a label objektum létrehozása elé.

app01/
  |-.vscode/
  |   |-launch.json
  |   `-settings.json
  |-bin/
  |-lib/
  |-resouces/
  |   `-images/
  |       `-kep01.png
  |-src/
  |  `-App.java
  `-README.md

Szöveg igazítása:

label1.setAligment(Pos.CENTER);

Ügyeljünk a label1 szélességére. Tegyük egy konténerben, amiben a mérete teljes szélességű.

Abszolút pozíciónálás:

    public void start(Stage stage) throws Exception {
 
        Pane pane = new Pane();
        Label label1 = new Label("Első");
        Label label2 = new Label("Második");
        label1.setLayoutX(50);
        label1.setLayoutY(50);
        label2.setLayoutX(50);
        label2.setLayoutY(70);
        pane.getChildren().addAll(label1, label2);        
        Scene scene = new Scene(pane, 400, 300);
        stage.setScene(scene);
        stage.show();
    }

Nyomógomb

Importáljuk a gombot:

import javafx.scene.control.Button;

Példányosítjuk a start() metódusban, majd adjuk a panelhez:

Button button = new Button("Katt");
//...
root.getChildren().add(button);

A teljes kód:

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) {
        Button button = new Button("Mehet");
 
        StackPane root = new StackPane();
        root.getChildren().add(button);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
}

Nyomógomb eseménye

Szükségünk van két új osztályra:

import javafx.event.ActionEvent;
import javafx.event.EventHandler;

Adjunk a gombhoz eseménykezelést:

        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Kattintás volt");
            }
        });

A teljes kód:

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
 
public class App extends Application {
    @Override
    public void start(Stage stage) {
        Button button = new Button("Katt");
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Kattintás volt");
            }
        });
 
        StackPane root = new StackPane();
        root.getChildren().add(button);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

Kilépés programból:

stage.close();

Eseménykezelés lambda kifejezéssel a függelékben.

ToggleButton

import javafx.scene.control.ToggleButton;
...
 
ToggleButton toggleButton1 = new ToggleButton("Mehet");
...

A lenyomott állapot ellenőrzése:

boolean lenyomva = toggleButton1.isSelected();

Teljes kód:

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        ToggleButton toggleButton1 = new ToggleButton("Fent");
        ToggleButton toggleButton2 = new ToggleButton("Lenyomva");
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
 
        vbox.getChildren().add(toggleButton1);
        vbox.getChildren().add(toggleButton2);
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Valami");
        primaryStage.show();
    }
}

Elrendezés

Függőleges elrendezéshez használjuk a VBox osztályt:

VBox vbox = new VBox();
vbox.getChildren().addAll(label, button);

Vízszintes elrendezéshez HBox osztály használahtó.

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Felirat");
        Button button = new Button("Gomb");
        VBox vbox = new VBox();
        vbox.getChildren().addAll(label, button);
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

20 pixel a komponensek között:

VBox vbox = new VBox(20);

Két gomb függőlegesen

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
 
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) {
 
        Button button1 = new Button("Mehet");
        Button button2 = new Button("Mehet");
        button1.setOnAction(e -> onButton1Click());
        button2.setOnAction(e -> onButton2Click());
 
        StackPane root = new StackPane();
        VBox vbox = new VBox(10);
        vbox.getChildren().addAll(button1, button2);
        root.getChildren().add(vbox);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
    private void onButton1Click() {
        System.out.println("1-s gomb kattintás");
    }
    private void onButton2Click() {
        System.out.println("2-s gomb kattintás");
    }
 
}

Scene csere

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
 
public class App extends Application {
    Stage primaryStage;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
 
        Label label1 = new Label("Első");
        Button button1 = new Button("Másik");
        VBox vbox1 = new VBox();
        vbox1.getChildren().addAll(label1, button1);
        Scene scene1 = new Scene(vbox1, 300, 250);
 
        Label label2 = new Label("Második");
        Button button2 = new Button("Vissza");
        VBox vbox2 = new VBox();
        vbox2.getChildren().addAll(label2, button2);
        Scene scene2 = new Scene(vbox2, 300, 250);
 
        button1.setOnAction(e -> primaryStage.setScene(scene2));
        button2.setOnAction(e -> primaryStage.setScene(scene1));
 
        primaryStage.setScene(scene1);
        primaryStage.show();
    }
}

Párbeszédablak

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        Label label1 = new Label("Első");
        Button button1 = new Button("Másik");
        VBox vbox1 = new VBox();
        vbox1.getChildren().addAll(label1, button1);
        Scene scene1 = new Scene(vbox1, 300, 250);
 
        button1.setOnAction(e -> MsgBox.show("cím", "Valami"));
 
        primaryStage.setScene(scene1);
        primaryStage.show();
    }
}
MsgBox.java
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
 
public class MsgBox {
    public static void show(String title, String msg) {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setTitle(title);
 
        Label label = new Label(msg);
        Button button = new Button("Bezár");
        button.setOnAction(e -> stage.close());
        VBox vbox = new VBox();
        vbox.getChildren().addAll(label, button);
        vbox.setAlignment(Pos.CENTER);
 
        Scene scene = new Scene(vbox, 300, 250);
        stage.setScene(scene);
        stage.show();
    }
}

Dialógus ablak

Szükségünk van a showAndWait(); metódusra, mert máskülönben a System.out.println() nem várja meg az ablak bezárását.

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        Button goButton = new Button("Mehet");
        goButton.setOnAction(e -> {
            boolean result = DlgBox.show("cím", "Biztos?");
            System.out.println("válasz: " + result);
        });
        StackPane root = new StackPane();
        root.getChildren().add(goButton);
        Scene scene1 = new Scene(root, 300, 250);
        primaryStage.setScene(scene1);
        primaryStage.show();
    }
 
}
DlgBox.java
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
 
public class DlgBox {
    static boolean result;
 
    public static boolean show(String title, String msg) {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setTitle(title);
 
        Label label = new Label(msg);
        Button yesButton = new Button("Igen");
        Button noButton = new Button("Nem");
 
        yesButton.setOnAction(e -> {
            result = true;
            stage.close();
        });
        noButton.setOnAction(e -> {
            result = false;
            stage.close();
        });
        VBox vbox = new VBox();
        HBox hbox = new HBox(10);
        vbox.getChildren().addAll(label, hbox);
        vbox.setAlignment(Pos.CENTER);
        hbox.getChildren().addAll(yesButton, noButton);
        hbox.setAlignment(Pos.CENTER);
 
        Scene scene = new Scene(vbox, 300, 250);
        stage.setScene(scene);
        stage.showAndWait();
 
        return result;
    }
}

Üzenetdoboz

import javafx.scene.control.Alert;
...
 
Alert alert = new Alert(Alert.AlertType.INFORMATION);        
alert.setTitle("Címsor szöveg");
alert.setHeaderText("Fejrész szöveg");
alert.setContentText("Üzenet");
alert.showAndWait();

Teljes kód:

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Alert;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        Button showButton = new Button("Mutat");
        Alert alert = new Alert(Alert.AlertType.INFORMATION);        
        showButton.setOnAction(e -> {
            alert.setTitle("Címsor szöveg");
            alert.setHeaderText("Fejrész szöveg");
            alert.setContentText("Üzenet");
            alert.showAndWait();
        });
 
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
        vbox.getChildren().add(showButton);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

Beviteli

Bevitelhez a TextField osztály használjuk.

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField numInput = new TextField();
        Button doubleButton = new Button("Dupla");
        doubleButton.setOnAction(e -> {
            String numStr = numInput.getText();
            int num = Integer.parseInt(numStr);
            Integer result = num * 2;
            numInput.setText(result.toString());
        });
 
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(numInput, doubleButton);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

Jelszó

Jelszóbevitel

...
import javafx.scene.control.PasswordField;
 
...
 
PasswordField passInput = new PasswordField();
passInput.setPromptText("password");

A következő program egy felhasználónevet és jelszót kér be.

Teljes kód:

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Alert;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField userInput = new TextField();
        PasswordField passInput = new PasswordField();
        passInput.setPromptText("jelszó");
        Button loginButton = new Button("Belépés");
        Alert alert = new Alert(Alert.AlertType.INFORMATION);        
        loginButton.setOnAction(e -> {
            String user = userInput.getText();
            String pass = passInput.getText();
            System.out.printf("|%s|\n",user);
            System.out.printf("|%s|\n", pass);
            String msgStr = "";
            if(user.equals("janos") && pass.equals("titok")) {
                msgStr = "Azonosítás OK";
            }else {
                msgStr = "Hiba! Azonosítás sikertelen!";
            }
            alert.setContentText(msgStr);
            alert.showAndWait();
        });
 
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
 
        vbox.getChildren().add(userInput);
        vbox.getChildren().add(passInput);
        vbox.getChildren().add(loginButton);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

Rádiógomb

import javafx.scene.control.RadioButton;
...
 
RadioButton rb1 = new RadioButton();
rb1.setText("Valami");

Esetleg így:

RadioButton rb1 = new RadioButton("Valami");

Csoportosítás:

final ToggleGroup group1 = new ToggleGroup();        
RadioButton radio1 = new RadioButton("Emese");
RadioButton radio2 = new RadioButton("Béla");
 
radio1.setToggleGroup(group1);
radio2.setToggleGroup(group1);

A kiválasztott gomb vizsgálata:

System.out.println(radio1.isSelected() );

Teljes kód:

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        final ToggleGroup group1 = new ToggleGroup();        
        RadioButton radio1 = new RadioButton("Emese");
        RadioButton radio2 = new RadioButton("Béla");
        Button button1 = new Button("Választ");
 
        radio1.setToggleGroup(group1);
        radio2.setToggleGroup(group1);        
 
        button1.setOnAction(e -> {
            String valasztott = "";
            if(radio1.isSelected()) {
                valasztott = "Emese";
            }else {
                valasztott = "Béla";
            }
            System.out.println("Választott: " + valasztott);
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(radio1, radio2, button1);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

Link:

Jelőlönézet

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        CheckBox checkbox1 = new CheckBox("Emese");
        CheckBox checkbox2 = new CheckBox("Béla");
        Button button = new Button("Dupla");
 
        checkbox1.setSelected(true);
        button.setOnAction(e -> {
            if (checkbox1.isSelected()) {
                System.out.println("Emese ok");
            }
            if (checkbox2.isSelected()) {
                System.out.println("Béla ok");
            }
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(checkbox1, checkbox2, button);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

ChoiceBox

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        ChoiceBox<String> choicebox = new ChoiceBox<>();
 
        choicebox.setValue("Szilva");
        choicebox.getItems().add("szilva");
        choicebox.getItems().add("körte");
        choicebox.getItems().add("barack");
        choicebox.getItems().addAll("alma", "banán", "citrom");
 
        Button button = new Button("Mehet");
        button.setOnAction(e -> {
            System.out.println(choicebox.getValue());
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(choicebox, button);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

A szelekció változásának figyelése:

        choicebox.getSelectionModel().selectedItemProperty()
                .addListener((obj, oldValue, newValue) -> System.out.println(newValue));

ComboBox

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        ComboBox<String> combobox = new ComboBox<>();
 
        combobox.getItems().add("alma");
        combobox.getItems().add("körte");
        combobox.getItems().add("barack");
        combobox.getItems().addAll("szilva", "banán", "citrom");
        combobox.setValue("barack");
 
        Button button = new Button("Mehet");
        button.setOnAction(e -> {
            System.out.println(combobox.getValue());
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(combobox, button);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

Beállíthatunk olyan szöveget is, ami előzetesen megjelenik, de nem jelent kiválasztást:

//combobox.setValue("barack");
combobox.setPromptText("Válassz gyümölcsöt");

Ebben az esetben törölni kell a setValue() beállítást.

Változás figyelése:

combobox.setOnAction(e -> System.out.println("Valami ki lett választva"));

Szerkeszthetőség beállítása:

combobox.setEditable(true);

ListBox

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        ListView<String> list = new ListView<>();
        list.getItems().setAll("alma", "körte", "barack", "szilva");
 
        Button button = new Button("Mehet");
        button.setOnAction(e -> {
            System.out.println(list.getSelectionModel().getSelectedIndex());
            System.out.println(list.getSelectionModel().getSelectedItem());
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(list, button);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

Többsoros kijelölés:

App.java
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        ListView<String> list = new ListView<>();
        list.getItems().setAll("alma", "körte", "barack", "szilva");
 
        list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
 
        Button button = new Button("Mehet");
        button.setOnAction(e -> {
            ObservableList<String> obsList;
            obsList = list.getSelectionModel().getSelectedItems();
            for (String item : obsList) {
                System.out.println(item);
            }
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(list, button);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

TreeView

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        TreeView<String> tree;
        TreeItem<String> rootNode, progNode, databaseNode;
 
        rootNode = new TreeItem<>("Tanulnivaló");
 
        progNode = createNode("Programozás", rootNode);
        createNode("Java", progNode);
        createNode("Charp", progNode);
 
        databaseNode = createNode("Adatbázis", rootNode);
        createNode("MySQL", databaseNode);
        createNode("Mariadb", databaseNode);
 
        tree = new TreeView<>(rootNode);
 
        Button button = new Button("Vált");
        button.setOnAction(e -> {
            if (tree.isShowRoot())
                tree.setShowRoot(false);
            else
                tree.setShowRoot(true);
        });
 
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(tree, button);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public TreeItem<String> createNode(String title, TreeItem<String> parent) {
        TreeItem<String> node = new TreeItem<>(title);
        parent.getChildren().add(node);
        return node;
    }
 
}

A csomópont nyitása, zárása a setExpanded() metódussal lehetséges.

root.setExpanded(true);

A csomópont nyitva, vagy zárva van-e:

root.isExpanded()

Melyik elem lett kijelölve:

tree.getSelectionModel().selectedItemProperty().addListener((obj, odlNode, newNode) -> {
    if (newNode != null) {
        System.out.println(newNode.getValue());
    }
});

Még több:

Táblázat

Megjelenítés táblázatban

A táblázathoz a következő osztályok szükségesek:

  • TableView
  • TableColumn
  • PropertyValueFactory
  • ObservableList
  • FXCollections

Szükség van egy olyan osztályra, amiben tárolhatjuk a táblázat sorait. Legyen a példa kedvéért egy dolgozókat tároló osztály:

Employee.java
public class Employee {
    String name;
    String city;
    double salary;
 
    public Employee(String name, String city, double salary) {
        this.name = name;
        this.city = city;
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getCity() {
        return city;
    }
 
    public void setCity(String city) {
        this.city = city;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }   
 
}

Szükségünk lesz, minden mező számára beállító és lekérdező (getter, setter) függvényekre.

App.java
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
 
public class App extends Application {
 
    private final TableView<Employee> table = new TableView<>();
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
 
        TableColumn<Employee, String> nameCol = new TableColumn<>("Név");
        nameCol.setMinWidth(100);
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
 
        TableColumn<Employee, String> cityCol = new TableColumn<>("Település");
        cityCol.setMinWidth(100);
        cityCol.setCellValueFactory(new PropertyValueFactory<>("city"));
 
        TableColumn<Employee, Double> salaryCol = new TableColumn<>("Fizetés");
        salaryCol.setMinWidth(100);
        salaryCol.setCellValueFactory(new PropertyValueFactory<>("salary"));
 
        table.setItems(getEmployees());
 
        table.getColumns().add(nameCol);
        table.getColumns().add(cityCol);
        table.getColumns().add(salaryCol);
 
        Scene scene = new Scene(table, 302, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    private ObservableList<Employee> getEmployees() {
 
        ObservableList<Employee> employees = 
        FXCollections.observableArrayList(
                new Employee("Poros Béla", "Szeged", 2870000), 
                new Employee("Tér Irén", "Szeged", 2435000),
                new Employee("Pakos Péter", "Hatvan", 2530000), 
                new Employee("Szu Emese", "Szolnok", 2270000));
        return employees;
    }
 
}

A táblázat mezőit a table.getColumns().addAll() függvénnyel is felvehetjük, de ez típusbiztonsági figyelmeztetést eredményez, mivel ismétlődő típusok argumentumlistáját adjuk át.

Több kijelölhető sor beállítása:

table.getSelectionModel().setSelectionMode(
    SelectionMode.MULTIPLE
    ); 

Táblázat sorkezeléssel

Employee.java
public class Employee {
    String name;
    String city;
    Double salary;
 
    public Employee(String name, String city, double salary) {
        this.name = name;
        this.city = city;
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getCity() {
        return city;
    }
 
    public void setCity(String city) {
        this.city = city;
    }
 
    public Double getSalary() {
        return salary;
    }
 
    public void setSalary(Double salary) {
        this.salary = salary;
    }
 
}
App.java
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
 
public class App extends Application {
 
    private TableView<Employee> table = new TableView<>();
    private TextField nameInput, cityInput, salaryInput;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
 
        TableColumn<Employee, String> nameCol = new TableColumn<>("Név");
        nameCol.setMinWidth(100);
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
 
        TableColumn<Employee, String> cityCol = new TableColumn<>("Település");
        cityCol.setMinWidth(100);
        cityCol.setCellValueFactory(new PropertyValueFactory<>("city"));
 
 
        TableColumn<Employee, String> salaryCol = new TableColumn<>("Fizetés");
        salaryCol.setMinWidth(100);
        salaryCol.setCellValueFactory(new PropertyValueFactory<>("salary"));
 
 
 
        nameInput = new TextField();
        nameInput.setPromptText("Név");
 
        cityInput = new TextField();
        cityInput.setPromptText("Település");
 
        salaryInput = new TextField();
        salaryInput.setPromptText("Fizetés");
 
 
        Button addButton = new Button("Hozzáad");
        addButton.setOnAction(e->onClickAddButton());
        Button delButton = new Button("Törlés");
        delButton.setOnAction(e->onClickDelButton());
 
        HBox inputBox = new HBox(10);
        inputBox.setPadding(new Insets(10, 10, 10, 10));
        inputBox.setSpacing(10);
        inputBox.getChildren().addAll(
            nameInput, cityInput, salaryInput
        );
        HBox buttonBox = new HBox(10);
        buttonBox.setPadding(new Insets(10, 10, 10, 10));
        buttonBox.setSpacing(10);
        buttonBox.getChildren().addAll(
            addButton, delButton
        );
 
 
        VBox vbox = new VBox();
        vbox.getChildren().addAll(table, inputBox, buttonBox);
 
        table.setItems(getEmployees());
 
        table.getColumns().add(nameCol);
        table.getColumns().add(cityCol);
        table.getColumns().add(salaryCol);
 
        Scene scene = new Scene(vbox, 302, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    private void onClickAddButton() {
        String name = this.nameInput.getText();
        String city = this.cityInput.getText();
        double salary = Double.parseDouble(this.salaryInput.getText());
        Employee employee = new Employee(name, city, salary);
        table.getItems().add(employee);
        this.nameInput.clear();
        this.cityInput.clear();
        this.salaryInput.clear();
    }
 
    private void onClickDelButton() {
        ObservableList<Employee> selectedEmployee, employees;
        employees = table.getItems();
        selectedEmployee = table.getSelectionModel().getSelectedItems();
        selectedEmployee.forEach(employees::remove);
    }
 
    private ObservableList<Employee> getEmployees() {
 
        ObservableList<Employee> employees = 
        FXCollections.observableArrayList(
                new Employee("Poros Béla", "Szeged", 2870000), 
                new Employee("Tér Irén", "Szeged", 2435000),
                new Employee("Pakos Péter", "Hatvan", 2530000), 
                new Employee("Szu Emese", "Szolnok", 2270000));
        return employees;
    }
 
}

Szerkeszthető cellák

Az Employee osztályban a salary mezőt beállító, lekérdező metódusokat átírtuk. A lekérő String típust ad vissza, a beállító String típust fogad, de átalakítja Double típussá.

Employee.java
public class Employee {
    String name;
    String city;
    Double salary;
 
    public Employee(String name, String city, double salary) {
        this.name = name;
        this.city = city;
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getCity() {
        return city;
    }
 
    public void setCity(String city) {
        this.city = city;
    }
 
    public String getSalary() {
        return salary.toString();
    }
 
    public void setSalary(String salary) {
        this.salary = Double.parseDouble(salary);
    }
 
}
App.java
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
import javafx.event.EventHandler;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.TextFieldTableCell;
 
public class App extends Application {
 
    private TableView<Employee> table = new TableView<>();
    private TextField nameInput, cityInput, salaryInput;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
 
        TableColumn<Employee, String> nameCol = new TableColumn<>("Név");
        nameCol.setMinWidth(100);
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
 
        TableColumn<Employee, String> cityCol = new TableColumn<>("Település");
        cityCol.setMinWidth(100);
        cityCol.setCellValueFactory(new PropertyValueFactory<>("city"));
 
 
        TableColumn<Employee, String> salaryCol = new TableColumn<>("Fizetés");
        salaryCol.setMinWidth(100);
        salaryCol.setCellValueFactory(new PropertyValueFactory<>("salary"));
 
 
        nameCol.setCellFactory(
            TextFieldTableCell.<Employee>forTableColumn()    
        );
 
        cityCol.setCellFactory(
            TextFieldTableCell.<Employee>forTableColumn()    
        );
 
        salaryCol.setCellFactory(
            TextFieldTableCell.<Employee>forTableColumn()    
        );
 
        nameCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Employee, String>>() {
                @Override
                public void handle(CellEditEvent<Employee, String> t) {
                    ((Employee) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setName(t.getNewValue());
                }
            }
        );
 
        cityCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Employee, String>>() {
                @Override
                public void handle(CellEditEvent<Employee, String> t) {
                    ((Employee) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setCity(t.getNewValue());
                }
            }
        );
 
        salaryCol.setOnEditCommit(
            new EventHandler<CellEditEvent<Employee, String>>() {
                @Override
                public void handle(CellEditEvent<Employee, String> t) {
                    ((Employee) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setSalary(t.getNewValue());
                }
            }
        );
 
        table.setEditable(true);
 
        nameInput = new TextField();
        nameInput.setPromptText("Név");
 
        cityInput = new TextField();
        cityInput.setPromptText("Település");
 
        salaryInput = new TextField();
        salaryInput.setPromptText("Fizetés");
 
 
        Button addButton = new Button("Hozzáad");
        addButton.setOnAction(e->onClickAddButton());
        Button delButton = new Button("Törlés");
        delButton.setOnAction(e->onClickDelButton());
 
        HBox inputBox = new HBox(10);
        inputBox.setPadding(new Insets(10, 10, 10, 10));
        inputBox.setSpacing(10);
        inputBox.getChildren().addAll(
            nameInput, cityInput, salaryInput
        );
        HBox buttonBox = new HBox(10);
        buttonBox.setPadding(new Insets(10, 10, 10, 10));
        buttonBox.setSpacing(10);
        buttonBox.getChildren().addAll(
            addButton, delButton
        );
 
 
        VBox vbox = new VBox();
        vbox.getChildren().addAll(table, inputBox, buttonBox);
 
        table.setItems(getEmployees());
 
        table.getColumns().add(nameCol);
        table.getColumns().add(cityCol);
        table.getColumns().add(salaryCol);
 
        Scene scene = new Scene(vbox, 302, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    private void onClickAddButton() {
        String name = this.nameInput.getText();
        String city = this.cityInput.getText();
        double salary = Double.parseDouble(this.salaryInput.getText());
        Employee employee = new Employee(name, city, salary);
        table.getItems().add(employee);
        this.nameInput.clear();
        this.cityInput.clear();
        this.salaryInput.clear();
    }
 
    private void onClickDelButton() {
        ObservableList<Employee> selectedEmployee, employees;
        employees = table.getItems();
        selectedEmployee = table.getSelectionModel().getSelectedItems();
        selectedEmployee.forEach(employees::remove);
    }
 
    private ObservableList<Employee> getEmployees() {
 
        ObservableList<Employee> employees = 
        FXCollections.observableArrayList(
                new Employee("Poros Béla", "Szeged", 2870000), 
                new Employee("Tér Irén", "Szeged", 2435000),
                new Employee("Pakos Péter", "Hatvan", 2530000), 
                new Employee("Szu Emese", "Szolnok", 2270000));
        return employees;
    }
 
}

GridPane

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane grid = new GridPane();
        grid.setVgap(10);
        grid.setHgap(10);
        grid.setPadding(new Insets(10, 10, 10, 10));
 
        Label baseLabel = new Label("Alap: ");
        GridPane.setConstraints(baseLabel, 0, 0);
 
        TextField baseInput = new TextField();
        GridPane.setConstraints(baseInput, 1, 0);
 
        Label heightLabel = new Label("Magasság: ");
        GridPane.setConstraints(heightLabel, 0, 1);
 
        TextField heightInput = new TextField();
        GridPane.setConstraints(heightInput, 1, 1);
 
        Button calcButton = new Button("Számít");
        GridPane.setConstraints(calcButton, 1, 2);
 
        grid.getChildren().addAll(baseLabel, baseInput, heightLabel, heightInput, calcButton);
 
        Scene scene = new Scene(grid, 300, 150);
        primaryStage.setScene(scene);
 
        primaryStage.show();
    }
 
}

App.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        Menu fileMenu = new Menu("Segítség");
        fileMenu.getItems().add(new MenuItem("Tartalom"));
        fileMenu.getItems().add(new MenuItem("Névjegy"));
 
        MenuBar menuBar = new MenuBar();
        menuBar.getMenus().addAll(fileMenu);
 
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(menuBar);
        Scene scene = new Scene(borderPane, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

App.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        MenuBar menuBar = new MenuBar();
        Menu helpMenu = new Menu("Segítség");
        MenuItem contentMenuItem = new MenuItem("Tartalom");
        MenuItem aboutMenuItem = new MenuItem("Névjegy");
 
        contentMenuItem.setOnAction(e->System.out.println("Tartalom"));
        aboutMenuItem.setOnAction(e->System.out.println("Névjegy"));
 
        helpMenu.getItems().addAll(contentMenuItem, aboutMenuItem);
        menuBar.getMenus().addAll(helpMenu);
 
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(menuBar);
        Scene scene = new Scene(borderPane, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Még több menü

App.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
 
public class App extends Application {
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        MenuBar menuBar = new MenuBar();
        Menu fileMenu = new Menu("Fájl");
        Menu helpMenu = new Menu("Segítség");
        MenuItem exitMenuItem = new MenuItem("Kilépés");
        MenuItem contentMenuItem = new MenuItem("Tartalom");
        MenuItem aboutMenuItem = new MenuItem("Névjegy");
 
        exitMenuItem.setOnAction(e->primaryStage.close());
        contentMenuItem.setOnAction(e->System.out.println("Tartalom"));
        aboutMenuItem.setOnAction(e->System.out.println("Névjegy"));
 
        fileMenu.getItems().addAll(exitMenuItem);
        helpMenu.getItems().addAll(contentMenuItem, aboutMenuItem);
        menuBar.getMenus().addAll(fileMenu, helpMenu);
 
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(menuBar);
        Scene scene = new Scene(borderPane, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

TabPane

TabPane tabPane = new TabPane();
Tab tab1 = new Tab("Nevek");
Tab tab2 = new Tab("Csoportok");
Tab tab3 = new Tab("Tárgyak");
 
tabPane.getTabs().add(tab1);
tabPane.getTabs().add(tab2);
tabPane.getTabs().add(tab3);

A fülek felirata és tartalma beállítható metódussal:

tab1.setText("Valami");
tab1.setContent(vbox1);

Fülek a panelhez egyetlen metódussal:

tabPane.getTabs().addAll(tab1, tab2);

Teljes kód:

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        TabPane tabPane = new TabPane();
        Tab tab1 = new Tab("Nevek");
        Tab tab2 = new Tab("Csoportok");
        Tab tab3 = new Tab("Tárgyak");
 
        tabPane.getTabs().add(tab1);
        tabPane.getTabs().add(tab2);
        tabPane.getTabs().add(tab3);
 
        VBox vbox = new VBox(tabPane);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Valami");
        primaryStage.show();
    }
}

Feliratok

TabPane tabPane = new TabPane();
Tab tab1 = new Tab("Nevek", new Label("Nevek megjelenítése"));
Tab tab2 = new Tab("Csoportok", new Label("Csoportok megjelenítése"));
Tab tab3 = new Tab("Tárgyak", new Label("Tárgyak megjelenítése"));
 
tabPane.getTabs().add(tab1);
tabPane.getTabs().add(tab2);
tabPane.getTabs().add(tab3);

Gombok a fülön

A füleken (tab) elhelyezhető elrendezéskezelő is. Ebben a példában az első fülön egy VBox elrendezéskezelőn két gombot helyeztünk el:

App.java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        Button tab1Button1 = new Button("Mehet");
        Button tab1Button2 = new Button("Jöhet");
 
        VBox tab1Vbox = new VBox();
        tab1Vbox.setPadding(new Insets(10, 10, 10, 10));
        tab1Vbox.setSpacing(10);
        tab1Vbox.getChildren().add(tab1Button1);
        tab1Vbox.getChildren().add(tab1Button2);
 
        TabPane tabPane = new TabPane();
        Tab tab1 = new Tab("Nevek", tab1Vbox);
        Tab tab2 = new Tab("Csoportok", new Label("Csoportok megjelenítése"));
        Tab tab3 = new Tab("Tárgyak", new Label("Tárgyak megjelenítése"));
 
        tabPane.getTabs().add(tab1);
        tabPane.getTabs().add(tab2);
        tabPane.getTabs().add(tab3);
 
        VBox vbox = new VBox(tabPane);
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
 
        Scene scene = new Scene(vbox, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Valami");
        primaryStage.show();
    }
}

Hibás feladatok

Két gomb

A következő program két gombot jelenít meg. Az felső gomb kattintásra ki kellene írja: „1-s gomb kattintás”. Az alsó gomb kattintásra ki kellene írja: „2-s gomb kattintás”. Azonban a felső gombra kattintásnál ezt írj ki: „2-s gomb kattintás”. Az alsó gombra kattintva nem történik semmi. Hol a hiba?

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
 
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) {
 
        Button button1 = new Button("Felső");
        Button button2 = new Button("Alsó");
        button1.setOnAction(e -> onButton1Click());
        button1.setOnAction(e -> onButton2Click());
 
        StackPane root = new StackPane();
        VBox vbox = new VBox(10);
        vbox.getChildren().addAll(button1, button2);
        root.getChildren().add(vbox);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
    private void onButton1Click() {
        System.out.println("1-s gomb kattintás");
    }
    private void onButton2Click() {
        System.out.println("2-s gomb kattintás");
    }
 
}

Függelék

Label képpel

Teljes kód:

App.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
 
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Font;
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
    private ImageView getImage() {
        ImageView imageView = null;
        try {
            imageView = tryGetImage();
        } catch (Exception e) {
            System.err.println("Hiba! A fájl nem található");
        }
        return imageView;
    }
 
    private ImageView tryGetImage() throws FileNotFoundException{
        String iconPath = "resources/images/kep02.png";
        FileInputStream input = new FileInputStream(iconPath);
        Image image = new Image(input);
        ImageView imageView = new ImageView(image);
        return imageView;
    }
 
    @Override
    public void start(Stage stage) {
        Label label = new Label("Helló", getImage());
        label.setFont(new Font("Arial", 24));
        Scene scene = new Scene(label, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
}

A fájlbetöltése itt átkerült külön metódusba.

Gomb lambda eseménykezeléssel

App.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
 
 
public class App extends Application {
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) {
        Button button = new Button("Mehet");
        button.setOnAction(e -> onButtonClick());
 
        StackPane root = new StackPane();
        root.getChildren().add(button);
        Scene scene = new Scene(root, 300, 250);
        stage.setScene(scene);
        stage.setTitle("Valami");
        stage.show();
    }
 
    private void onButtonClick() {
        System.out.println("Kattintás volt");
    }
 
}

Linkek

oktatas/programozas/java/java_fx/tananyag.txt · Utolsó módosítás: 2023/04/01 21:44 szerkesztette: admin