如何在JavaFx中连接按钮侦听器 [英] How to connect button listener in javaFx

查看:65
本文介绍了如何在JavaFx中连接按钮侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎很简单,但是我必须采用一种特定的方式来实现导致混乱的代码.因此,在步骤3中,我需要向事件处理程序注册源对象. ButtonHandler类已经为我设置了,但是我不知道如何连接它们来注册按钮.获得的资源似乎使用不同的逻辑来连接javaFx事件,并且我无法在此代码应使用的逻辑与给出的逻辑之间建立连接.

The question seems simple, but there is a specific way I have to implement my code that is causing confusion. So in step #3 I need to register the source object with the event handler. The ButtonHandler class is already set up for me but I can't figure how to connect these to register the button. The resources I was given appears to use different logic to connect javaFx events and I can not make a connection between the logic this code should use with the logic I was given.

如果需要,我可以进一步详细说明并提供更多代码.

I can elaborate further and provide more code if needed.

import java.util.ArrayList;
import javax.swing.plaf.basic.BasicButtonListener;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
//import all other necessary javafx classes here
//----

public class InputPane extends HBox
{
    //GUI components
    private ArrayList<Laptop> laptopList;

    //The relationship between InputPane and PurchasePane is Aggregation
    private PurchasePane purchasePane;
    //----
    private GridPane Gpane, RightPane;
    private Label label, l2, l3, l4, l5, errL;
    private Button btn1;
    private TextField text, t2, t3, t4, t5;
    private TextArea ta;

    //constructor
    public InputPane(ArrayList<Laptop> list, PurchasePane pPane)
    {
        laptopList = list;
        purchasePane = pPane;

        //Step #1: initialize each instance variable and set up the layout
        //----
        //create a GridPane hold those labels & text fields
        //consider using .setPadding() or setHgap(), setVgap()
        //to control the spacing and gap, etc.
        //----

        Gpane = new GridPane();
        Gpane.setHgap(10);
        Gpane.setVgap(10);
        Gpane.setPadding(new Insets(30, 30, 10, 20));

        label = new Label("Brand");
        l2 = new Label("Model");
        l3 = new Label("CPU(GHz)");
        l4 = new Label("RAM(GB)");
        l5 = new Label("Price($)");

        Gpane.add(label, 0, 0);
        Gpane.add(l2, 0, 1);
        Gpane.add(l3, 0, 2);
        Gpane.add(l4, 0, 3);
        Gpane.add(l5, 0, 4);

        //You might need to create a sub pane to hold the button
        //----
        btn1 = new Button("Enter a Laptop Info");
        btn1.setOnAction(new ButtonHandler());

        Gpane.add(btn1, 1, 5);
        //Set up the layout for the left half of the InputPane.
        //----
        text = new TextField();
        t2 = new TextField();
        t3 = new TextField();
        t4 = new TextField();
        t5 = new TextField();
        Gpane.add(text, 1, 0);
        Gpane.add(t2, 1, 1);
        Gpane.add(t3, 1, 2);
        Gpane.add(t4, 1, 3);
        Gpane.add(t5, 1, 4);

        errL = new Label("");
        errL.setVisible(false);
        Gpane.add(errL, 0, 0);
        //the right half of the InputPane is simply a TextArea object
        //Note: a ScrollPane will be added to it automatically when there are no
        //enough space
        RightPane = new GridPane();
        ta = new TextArea();
        ta.setPromptText("No laptops");
        ta.setPrefColumnCount(30);
        ta.setPrefRowCount(20);
        RightPane.add(ta, 8, 0);
        //Add the left half and right half to the InputPane
        getChildren().add(Gpane);

        getChildren().add(RightPane);
        //Note: InputPane extends from HBox
        //----

        //Step #3: register source object with event handler
        //---

    } //end of constructor

    //Step #2: Create a ButtonHandler class
    //ButtonHandler listens to see if the buttont "Enter a Laptop Info." is
    //pushed or not,
    //When the event occurs, it get a laptop's brand, model, CPU, RAM and price
    //information from the relevant text fields, then create a new Laptop
    //object and add it inside
    //the laptopList. Meanwhile it will display the laptop's information
    //inside the text area.
    //It also does error checking in case any of the textfields are empty or
    // wrong data was entered.
    private class ButtonHandler implements EventHandler<ActionEvent>
    {
        //Override the abstact method handle()
        @Override
        public void handle(ActionEvent e)
        {
            //declare any necessary local variables here
            //---
            String Brand, Model, CPU, RAM, Price;
            Brand = text.getText();
            Model = t2.getText();
            CPU = t3.getText();
            RAM = t4.getText();
            Price = t5.getText();

            //when a text field is empty and the button is pushed
            if
            (text.equals("")||t2.equals("")||t3.equals("")||t4.equals("")||
                    t5.equals(""))
            {
                errL.setText("Empty Fields");
                errL.setVisible(true);
            }

            else    //for all other cases
            {
                try {
                    Laptop lap = new Laptop(Brand, Model, Double.parseDouble(CPU),
                            Double.parseDouble(RAM), Double.parseDouble(Price));
                    laptopList.add(lap);
                    ta.appendText(lap.toString());
                    errL.setText("Laptop added");
                    text.setText(""); t2.setText(""); t3.setText("");
                    t4.setText(""); t5.setText("");
                    //----
                    //at the end, don't forget to update the new arrayList
                    //information on the ListView of the Purchase Pane
                    //----
                    purchasePane.updateLaptopList(lap);
                    //Also somewhere you will need to use try & catch block to catch
                    //the NumberFormatException

                }catch (NumberFormatException l) {
                    System.err.println("Numbers only");
                }
            }

        } //end of handle() method
    } //end of ButtonHandler class
}

推荐答案

使用Button类的setOnAction方法定义用户单击按钮时将发生的情况.

Use the setOnAction method of the Button class to define what will happen when a user clicks the button.

此代码段说明了如何在方法中使用任意类:

This snippet of code explain how we use anynomous class in method :

button.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
        label.setText("Accepted");
    }
});

我们可以在自定义类中覆盖handle方法,并像这样添加它:

We can override handle method in custom class and add it like this :

button.setOnAction(new CustomHandle());

您应该知道ActionEvent是EventHandler处理的事件类型. EventHandler对象提供了handle方法来处理为按钮触发的操作.

You should know that ActionEvent is an event type that is processed by EventHandler. An EventHandler object provides the handle method to process an action fired for a button.

您可以使用Button类设置导致特定行为或应用视觉效果所需的尽可能多的事件处理方法.在这种情况下,我们使用button.addEventHandler(EventType,EventObject).

You can use the Button class to set as many event-handling methods as you need to cause the specific behavior or apply visual effects.In this case we use button.addEventHandler(EventType,EventObject).

button.addEventHandler(MouseEvent.MOUSE_ENTERED, 
    new EventHandler<MouseEvent>() {
        @Override public void handle(MouseEvent e) {
            button.setEffect(shadow);
        }
});

这篇关于如何在JavaFx中连接按钮侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆