JavaFX | Кнопка с примерами

Опубликовано: 13 Февраля, 2022

Класс кнопки является частью пакета JavaFX и может содержать текст, графику или и то, и другое.

Кнопка в JavaFX может быть трех разных типов:

  1. Обычная кнопка: обычная кнопка
  2. Кнопка по умолчанию: кнопка по умолчанию, которая получает нажатие клавиатуры VK_ENTER.
  3. Кнопка отмены: кнопка отмены, которая получает нажатие клавиатуры VK_ENTER.

При нажатии кнопки отправляется событие действия. Этим событием действия можно управлять с помощью EventHandler. Кнопки также могут реагировать на события мыши, реализуя EventHandler для обработки MouseEvent.

Конструкторами класса Button являются :

  1. Button () : создает кнопку с пустой строкой в качестве метки.
  2. Кнопка (String t) : создает кнопку с указанным текстом в качестве метки.
  3. Кнопка (String t, Node g) : создает кнопку с указанным текстом и значком для ее метки.

Обычно используемые методы :

метод объяснение
setCancelButton (логическое значение v) Устанавливает значение свойства cancelButton.
setDefaultButton (логическое значение v) Устанавливает значение свойства defaultButton
isDefaultButton () Получает значение свойства defaultButton.
isCancelButton () Получает значение свойства cancelButton.
cancelButtonProperty () Кнопка отмены - это кнопка, на которую нажимается клавиатура VK_ESC.
defaultButtonProperty () Кнопка по умолчанию - это кнопка, на которую с клавиатуры нажимается VK_ENTER.
createDefaultSkin () Создайте новый экземпляр обложки по умолчанию для этого элемента управления.

Below programs illustrate the use of Button in JavaFX.

  1. Program to create a button and add it to the stage: This program creates a Button indicated by the name b. The button will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.
    // Java Program to create a button and add it to the stage
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    public class button extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating buttons");
      
            // create a button
            Button b = new Button("button");
      
            // create a stack pane
            StackPane r = new StackPane();
      
            // add button
            r.getChildren().add(b);
      
            // create a scene
            Scene sc = new Scene(r, 200, 200);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

  2. Java program to create a button and add event handler to it: This program creates a Button indicated by the name b. The button will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function.
    // Java program to create a button and add event handler to it
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
    public class button_1 extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating buttons");
      
            // create a button
            Button b = new Button("button");
      
            // create a stack pane
            TilePane r = new TilePane();
      
            // create a label
            Label l = new Label("button not selected");
      
            // action event
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    l.setText("   button   selected    ");
                }
            };
      
            // when button is pressed
            b.setOnAction(event);
      
            // add button
            r.getChildren().add(b);
            r.getChildren().add(l);
      
            // create a scene
            Scene sc = new Scene(r, 200, 200);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

  3. Java Program to create a button with a image and add event handler to it: This program creates a Button with an image on it indicated by the name b. The image will be included using the File Input Stream that imports the image. we will then create an image using the object of file input stream and then create an image view using the image file. The button will be created inside a scene, which in turn will be hosted inside a stage.we would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function.
    // Java Program to create a button with a image and
    // add event handler to it
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.scene.image.*;
    import java.io.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
    import java.net.*;
    public class button_2 extends Application {
      
        // launch the application
        public void start(Stage s) throws Exception
        {
            // set title for the stage
            s.setTitle("creating buttons");
      
            // create a input stream
            FileInputStream input = new FileInputStream("f:\gfg.png");
      
            // create a image
            Image i = new Image(input);
      
            // create a image View
            ImageView iw = new ImageView(i);
      
            // create a button
            Button b = new Button("", iw);
      
            // create a stack pane
            TilePane r = new TilePane();
      
            // create a label
            Label l = new Label("button not selected");
      
            // action event
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    l.setText("button selected    ");
                }
            };
      
            // when button is pressed
            b.setOnAction(event);
      
            // add button
            r.getChildren().add(b);
            r.getChildren().add(l);
      
            // create a scene
            Scene sc = new Scene(r, 200, 200);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output

  4. Java Program to create a button with a image and text and add event handler to it

    This program creates a Button with an image and a text on it indicated by the name b. The image will be included using the File Input Stream that imports the image. we will then create an image using the object of file input stream and then create an image view using the image file.The button will be created inside a scene, which in turn will be hosted inside a stage.we would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function.

    // Java Program to create a button with a image
    // and text and add event handler to it
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.scene.image.*;
    import java.io.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
    import java.net.*;
    public class button_3 extends Application {
      
        // launch the application
        public void start(Stage s) throws Exception
        {
            // set title for the stage
            s.setTitle("creating buttons");
      
            // create a input stream
            FileInputStream input = new FileInputStream("f:\gfg.png");
      
            // create a image
            Image i = new Image(input);
      
            // create a image View
            ImageView iw = new ImageView(i);
      
            // create a button
            Button b = new Button("Button", iw);
      
            // create a stack pane
            TilePane r = new TilePane();
      
            // create a label
            Label l = new Label("button not selected");
      
            // action event
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    l.setText("button selected    ");
                }
            };
      
            // when button is pressed
            b.setOnAction(event);
      
            // add button
            r.getChildren().add(b);
            r.getChildren().add(l);
      
            // create a scene
            Scene sc = new Scene(r, 200, 200);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

  5. Java program to create a default button and a cancel button: This program creates a Button indicated by the name b and b1 . The button b will act as a cancel button which will respond to the escape keypress of keyboard and button b1 will behave as a default button which will respond to enter keypress of the keyboard). The button will be created inside a scene, which in turn will be hosted inside a stage.we would create a label to show which button is pressed. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function.
    // Java program to create a default button and a
    // cancel button and add event handler to it
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
    public class button_4 extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating buttons");
      
            // create a button
            Button b = new Button("cancel button");
      
            // set cancel button
            b.setCancelButton(true);
      
            // create a button
            Button b1 = new Button("default button");
      
            // set default button
            b1.setDefaultButton(true);
      
            // create a stack pane
            TilePane r = new TilePane();
      
            // create a label
            Label l = new Label("button not selected");
      
            // action event
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    l.setText("  cancel  button    selected    ");
                }
            };
            EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    l.setText("  default button   selected    ");
                }
            };
      
            // when button is pressed
            b.setOnAction(event);
            b1.setOnAction(event1);
      
            // add button
            r.getChildren().add(b);
            r.getChildren().add(b1);
            r.getChildren().add(l);
      
            // create a scene
            Scene sc = new Scene(r, 200, 200);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

Note: The above programs might not run in an online IDE please use an offline compiler.

Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Button.html

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.