Wednesday 30 May 2018

JavaFX: Create Toggle Button

ToggleButton class provides below constructors to create ToggleButton objects.

public ToggleButton()
public ToggleButton(String text)
public ToggleButton(String text, Node graphic)

Ex
ToggleButton toggleButton1 = new ToggleButton();
toggleButton1.setText("Toggle Button 1");

ToggleButton toggleButton2 = new ToggleButton("Toggle Button 2");

InputStream is = new FileInputStream(imageFilePath);
Image image = new Image(is);
ToggleButton toggleButton3 = new ToggleButton("toggle button 3", new ImageView(image));

Find the below working example.

ToggleButtonApp.java
package com.sample.demos;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ToggleButtonApp extends Application {
 private static String imageFilePath = "C:\\Users\\krishna\\Documents\\Study\\javaFX\\javaIcon.png";

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {
  ToggleGroup toggleGroup = new ToggleGroup();

  ToggleButton toggleButton1 = new ToggleButton();
  toggleButton1.setText("Toggle Button 1");

  ToggleButton toggleButton2 = new ToggleButton("Toggle Button 2");

  InputStream is = new FileInputStream(imageFilePath);
  Image image = new Image(is);
  ToggleButton toggleButton3 = new ToggleButton("toggle button 3", new ImageView(image));

  toggleButton1.setToggleGroup(toggleGroup);
  toggleButton2.setToggleGroup(toggleGroup);
  toggleButton3.setToggleGroup(toggleGroup);
  
  HBox hbox = new HBox(toggleButton1, toggleButton2, toggleButton3);

  hbox.setAlignment(Pos.TOP_CENTER);

  Scene scene = new Scene(hbox, 800, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Toggle Button Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(ToggleButtonApp.class, args);
 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment