简体   繁体   中英

How to connect button listener in 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
}

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");
    }
});

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

button.setOnAction(new CustomHandle());

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.

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);
        }
});

如@c0der btn1.setOnAction(new ButtonHandler());所指出的那样,向btn1.setOnAction(new ButtonHandler());注册ButtonHandler btn1.setOnAction(new ButtonHandler());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM