【Java】Java Project 挑战系列第8篇:Java Graphical User Interface (GUI): JavaFX FXML and Event Handling

本文介绍了使用JavaFXFXML创建用户界面的步骤,包括加载FXML源文件、修改导入语句、创建GridPane布局、添加文本和密码字段、按钮及文本元素。同时讲解了JavaFX中的事件处理,如按钮点击事件,以及Lambda表达式的应用,用于简化代码和事件监听器的创建。
摘要由CSDN通过智能技术生成

JavaFX FXML:

JavaFX FXML is an XML-based language that provides the structure for building a user interface separate from the application logic of your code.、

• Step 1: Load the FXML source file with the java file:

In this step, you will create a Java class and load the FXML source file in it. This allows you to access the user interface elements defined in the FXML file from your Java code. You can do this using the FXMLLoader class in JavaFX.

Here's an example code snippet to load the FXML file named "sample.fxml":

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("FXML Example");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

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

java

• Step 2: Modify the import statements in the fxml file.

When you create an FXML file, it includes import statements for JavaFX classes that are used in the file. However, if you load the FXML file from a different package or if you have renamed the JavaFX classes in your code, you may need to modify these import statements.

For example, if you want to use the Button class in your FXML file, you would include the following import statement:

<?import javafx.scene.control.Button?>

• Step 3: Create a gridPane layout in the fxml file.

In JavaFX, you typically use layout panes to arrange the user interface elements in your application. The GridPane is a commonly used layout pane that allows you to arrange elements in rows and columns.

To create a GridPane layout in your FXML file, you would include the following code:

<GridPane>
    <!-- Add user interface elements here -->
</GridPane>

• Step 4: Add text and password Fields in the fxml file.

You can add text fields and password fields to your FXML file by including the TextField and PasswordField classes, respectively.

Here's an example code snippet to add a text field and a password field to your FXML file:

<GridPane>
    <Label text="Username:" />
    <TextField fx:id="usernameField" GridPane.columnIndex="1" />

    <Label text="Password:" />
    <PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="1" />
</GridPane>

In this example, we've added a Label for the username and password fields, as well as a TextField and a PasswordField. We've also specified the fx:id for each element, which allows us to access it from our Java code.

• Step 5: Add a button and text in the fxml file.

You can add a button to your FXML file using the Button class. You can also add a text element using the Label class.

Here's an example code snippet to add a button and a text element to your FXML file:

<GridPane>
    <!-- Add text and password fields here -->

    <Button text="Login" onAction="#loginButtonClicked" GridPane.columnIndex="1" GridPane.rowIndex="2" />

    <Label fx:id="messageLabel" GridPane.columnIndex="1" GridPane.rowIndex="3" />
</GridPane>

In this example, we've added a Button with the text "Login", as well as a Label for displaying messages. We've also specified the onAction property for the Button, which specifies the method to be called when the button is clicked.

• Step 6: Add code to handle an event in the java file.

In the final step, you will add code to handle the event when the button is clicked. You can do this by defining a method in your Java code and specifying it in the onAction property of the Button in your FXML file.

Here's an example code snippet to handle the button click event:

FXML file:

<Button text="Login" onAction="#loginButtonClicked" GridPane.columnIndex="1" GridPane.rowIndex="2" />

Java code:

public class Controller {
    @FXML private TextField usernameField;
    @FXML private PasswordField passwordField;
    @FXML private Label messageLabel;

    @FXML
    private void loginButtonClicked(ActionEvent event) {
        String username = usernameField.getText();
        String password = passwordField.getText();

        if (username.equals("admin") && password.equals("password")) {
            messageLabel.setText("Login successful!");
        } else {
            messageLabel.setText("Invalid username or password.");
        }
    }
}

In this example, we've defined a method called "loginButtonClicked" in our Controller class. This method gets the text from the username and password fields, checks if they match a predefined username and password, and sets the text of the messageLabel accordingly.

We've also specified this method in the onAction property of the Button in our FXML file. When the button is clicked, the loginButtonClicked method will be called and the appropriate message will be displayed.

JavaFX Event Handling

JavaFX Event Handling: Convenient Methods

JavaFX provides convenient methods to handle events (create and register event handlers to respond to KeyEvent, MouseEvent, Action Event, Drag and Drop Events).

Button button = new Button("Click me!");
button.setOnAction(event -> {
    System.out.println("Button clicked!");
});

In this example, we've created a Button object and set an event handler using the setOnAction method. When the button is clicked, the lambda expression (event -> {...}) will be executed and the message "Button clicked!" will be printed to the console.

JavaFX Event Handling: Event Filters

Event Filters process the events in the Event capturing phase. JavaFX enables us to register a single event filter for more than one node and more than one type.

// create event filter
EventHandler<MouseEvent> eventFilter = event -> {
    System.out.println("Event captured by filter: " + event.getEventType());
};

// register event filter for multiple nodes
Node node1 = new Button("Button 1");
node1.addEventFilter(MouseEvent.MOUSE_CLICKED, eventFilter);

Node node2 = new Button("Button 2");
node2.addEventFilter(MouseEvent.MOUSE_CLICKED, eventFilter);

In this example, we've created an event filter using a lambda expression that prints a message to the console when a mouse click event is captured. We've then registered this event filter for two different Button nodes using the addEventFilter method.

JavaFX Event Handling: Event Handlers

Event Handlers are used to handle the events in the event bubbling phase. One can register multiple handlers for a single node (or one handler for multiple nodes.).

// create event handlers
EventHandler<ActionEvent> handler1 = event -> {
    System.out.println("Handler 1 executed!");
};

EventHandler<ActionEvent> handler2 = event -> {
    System.out.println("Handler 2 executed!");
};

// register event handlers for button
Button button = new Button("Click me!");
button.setOnAction(handler1.andThen(handler2));

In this example, we've created two event handlers using lambda expressions that print a message to the console when the button is clicked. We've then registered both of these event handlers for the button using the andThen method, which allows us to chain the handlers together.

(

A lambda expression is a feature introduced in Java 8 that allows you to create anonymous functions or closures. In other words, it's a way to create a block of code that can be passed around and executed later.

Here's an example of how to use a lambda expression in Java:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// using a lambda expression to filter even numbers
List<Integer> evenNumbers = numbers.stream()
                                    .filter(n -> n % 2 == 0)
                                    .collect(Collectors.toList());

In this example, we're using a lambda expression to filter even numbers from a list of integers. The expression n -> n % 2 == 0 defines a function that takes an integer n as input and returns a boolean value based on whether n is even or not. This lambda expression is then passed to the filter method of the Stream interface, which filters out all the odd numbers from the list.

Lambda expressions can be used in a variety of contexts, including collections, streams, and event handling in JavaFX. They can help make your code more concise and expressive, and can often replace the need for anonymous inner classes. In general, lambda expressions are a powerful tool for functional programming in Java, and can help you write more maintainable and efficient code.

)

这里挖一个坑,有机会一定继续分享关于lambda expressions 的细节。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值