Vertical menu for configuration panel - javafx-2

I would like to create configuration panel like this example:
The problem is that I don't how to create the vertical menu at the left side. Can you give some example of similar menu?

package verticalmenubar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.TabPane;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author reegan
*/
public class VerticalMenuBar extends Application {
public static TabPane tabPanel;
#Override
public void start(Stage primaryStage) {
BorderPane root = buildView();
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
BorderPane buildView() {
BorderPane root = new BorderPane();
tabPanel = new TabPane();
root.setCenter(tabPanel);
Accordion accordion = new Accordion();
Pane pane = null;
TitledPane tiledPane;
General1Bar general1 = new General1Bar();
pane= general1.getView();
tiledPane = new TitledPane("General1", pane);
accordion.getPanes().add(tiledPane);
General2Bar general2 = new General2Bar();
pane = general2.getView();
tiledPane = new TitledPane("General2", pane);
accordion.getPanes().add(tiledPane);
General3Bar general3 = new General3Bar();
pane = general3.getView();
tiledPane = new TitledPane("General3", pane);
accordion.getPanes().add(tiledPane);
root.setLeft(accordion);
return root;
}
public static void main(String[] args) {
launch(args);
}
}
class General1Bar {
public Pane getView() {
Pane p = new Pane();
Button button = new Button("One");
Button button1 = new Button("Two");
VBox vBox = new VBox(5);
vBox.getChildren().addAll(button,button1);
p.getChildren().addAll(vBox);
return p;
}
}
class General2Bar {
public Pane getView() {
Pane p = new Pane();
Button button = new Button("One");
Button button1 = new Button("Two");
VBox vBox = new VBox(5);
vBox.getChildren().addAll(button,button1);
p.getChildren().addAll(vBox);
return p;
}
}
class General3Bar {
public Pane getView() {
Pane p = new Pane();
Button button = new Button("One");
Button button1 = new Button("Two");
VBox vBox = new VBox(5);
vBox.getChildren().addAll(button,button1);
p.getChildren().addAll(vBox);
return p;
}
}
I am newly in javafx. please check this code if any wrong is there tell me..

Try Accordion control in javaFX Scene Builder.Following is XML Code of it.
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Accordion layoutX="14.0" layoutY="32.0">
<panes>
<TitledPane animated="false" text="untitled 1">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</TitledPane>
<TitledPane animated="false" text="untitled 2">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</TitledPane>
<TitledPane animated="false" text="untitled 3">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</TitledPane>
</panes>
</Accordion>
</children>
</AnchorPane>

Old question but it might still help somebody.
I wrote a piece about a custom vertical menu, take a look, I think you could use it to build your configuration panel.
http://synappse.co/blog/vertical-stateful-jfxtabpane-with-icons-in-javafx/

Related

JavaFX ObservableList toTableview via Task Thread

I am building a multiscreen JavaFX app with data being pulled from a SQL database to ObservableLists and displayed in the interface via Tableview. Because of the multiscreen nature of the app, I am trying to initialize the data from the ObservableList to the Tableview via the controller. The SQL pull to ObservableList is done via a Task on a new thread. When I include the sqlCSEditTbl.itemsProperty().setValue((ObservableList) csSQLList) in the Task method nothing is displayed in the TableView when I run the program. If I place the code outside the Task method,the particular screen will not display. I don't know what I am missing here to be able to get the data to display on the particular screen. I've debugged the SQL to ObservableList and the data is being properly stored in the ObservableList. The problem is getting it from the ObservableList to the Tableview interface. Any help would be greatly appreciated. Thank you!
App Edit Screen Screenshot
SQLCalcScript Array Model
package model.calcs;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Created by jdsmith on 2/17/2016.
*/
public class SQLCalcScripts {
private final IntegerProperty calcScriptID;
private final IntegerProperty calcScriptIndex;
private final StringProperty calcScriptName;
private final StringProperty calcScriptServer;
private final StringProperty calcScriptApp;
private final StringProperty calcScriptGroup;
public SQLCalcScripts() {
this(null, null, null, null, null, null);
}
public SQLCalcScripts(Integer calcScriptID, Integer calcScriptIndex, String calcScriptName, String calcScriptServer, String calcScriptApp, String calcScriptGroup) {
this.calcScriptID = new SimpleIntegerProperty(calcScriptID);
this.calcScriptIndex = new SimpleIntegerProperty(calcScriptIndex);
this.calcScriptName = new SimpleStringProperty(calcScriptName);
this.calcScriptServer = new SimpleStringProperty(calcScriptServer);
this.calcScriptApp = new SimpleStringProperty(calcScriptApp);
this.calcScriptGroup = new SimpleStringProperty(calcScriptGroup);
this.calcScriptID.addListener((e) -> System.out.println("ID changed to " + this.calcScriptID.get()));
this.calcScriptIndex.addListener((e) -> System.out.println("ID changed to " + this.calcScriptIndex.get()));
this.calcScriptName.addListener((e) -> System.out.println("ID changed to " + this.calcScriptName.get()));
this.calcScriptServer.addListener((e) -> System.out.println("ID changed to " + this.calcScriptServer.get()));
this.calcScriptApp.addListener((e) -> System.out.println("ID changed to " + this.calcScriptApp.get()));
this.calcScriptGroup.addListener((e) -> System.out.println("ID changed to " + this.calcScriptGroup.get()));
}
// Getters and Setters for Calc Script
public Integer getCalcScriptID() {
return calcScriptID.get();
}
public void setCalcScriptID(Integer calcScriptID) {
this.calcScriptID.set(calcScriptID);
}
public IntegerProperty calcScriptIDProperty() {
return calcScriptID;
}
public Integer getCalcScriptIndex() {
return calcScriptIndex.get();
}
public void setCalcScriptIndex(Integer calcScriptIndex) {
this.calcScriptIndex.set(calcScriptIndex);
}
public IntegerProperty calcScriptIndexProperty() {
return calcScriptIndex;
}
public String getCalcScriptName() {
return calcScriptName.get();
}
public void setCalcScriptName(String calcScriptName) {
this.calcScriptName.set(calcScriptName);
}
public StringProperty calcScriptNameProperty() {
return calcScriptName;
}
public String getCalcScriptServer() {
return calcScriptServer.get();
}
public void setCalcScriptServer(String calcScriptServer) {
this.calcScriptServer.set(calcScriptServer);
}
public StringProperty calcScriptServerProperty() {
return calcScriptServer;
}
public String getCalcScriptApp() {
return calcScriptApp.get();
}
public void setCalcScriptApp(String calcScriptApp) {
this.calcScriptApp.set(calcScriptApp);
}
public StringProperty calcScriptAppProperty() {
return calcScriptApp;
}
public String getCalcScriptGroup() {
return calcScriptGroup.get();
}
public void setCalcScriptGroup(String calcScriptGroup) {
this.calcScriptGroup.set(calcScriptGroup);
}
public StringProperty calcScriptGroupProperty() {
return calcScriptGroup;
}
}
csEditInterface.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="1080.0" prefWidth="1920.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="essapp.csEditController">
<children>
<VBox alignment="TOP_CENTER" prefHeight="200.0" prefWidth="100.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Label alignment="CENTER" contentDisplay="CENTER" text="Calculation Script Editor">
<font>
<Font name="System Bold" size="36.0" />
</font>
</Label>
<ScrollPane fitToHeight="true" fitToWidth="true" pannable="true" prefHeight="800.0" prefWidth="717.0">
<content>
<AnchorPane prefHeight="200.0" prefWidth="717.0">
<children>
<TableView editable="true" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="csEditID" editable="false" prefWidth="100.0" sortable="false" text="ID" />
<TableColumn fx:id="csEditIndex" prefWidth="100.0" text="Index" />
<TableColumn fx:id="csEditName" prefWidth="250.0" sortable="false" text="Name" />
<TableColumn fx:id="csEditServer" editable="false" prefWidth="300.0" sortable="false" text="Server" />
<TableColumn fx:id="csEditApp" editable="false" prefWidth="250.0" sortable="false" text="Application" />
<TableColumn fx:id="csEditGroup" prefWidth="400.0" sortable="false" text="Calc Group" />
</columns>
</TableView>
</children>
</AnchorPane>
</content>
<VBox.margin>
<Insets left="50.0" right="50.0" top="50.0" />
</VBox.margin>
</ScrollPane>
<Button fx:id="csEditOkBtn" defaultButton="true" mnemonicParsing="false" onAction="#createTbl" prefHeight="25.0" prefWidth="151.0" text="Commit Changes">
<VBox.margin>
<Insets top="50.0" />
</VBox.margin>
</Button>
<Button fx:id="csEditExitBtn" cancelButton="true" mnemonicParsing="false" onAction="#goToCSInt" prefHeight="25.0" prefWidth="150.0" text="Cancel">
<VBox.margin>
<Insets top="25.0" />
</VBox.margin>
</Button>
</children>
</VBox>
</children>
</AnchorPane>
csEditController Code:
package essapp;
import com.sun.javafx.tk.Toolkit;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;
import model.calcs.*;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import static javafx.scene.input.KeyCode.T;
#SuppressWarnings("Duplicates")
public class csEditController implements Initializable, ControlledScreen {
ScreensController myController;
ObservableList<SQLCalcScripts> csEditCSList = FXCollections.observableArrayList();
ObservableList<CalcScripts> csEditEssSQL = FXCollections.observableArrayList();
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
//Add SQL data to TableView
Task task = new Task<Void>() {
#Override
public Void call() throws Exception {
SQL2CalcScripts csSQLList = new SQL2CalcScripts();
csSQLList.sqlCalc("http://TEST-HYPRPT01:13080/aps/JAPI","GNLESB",csEditCSList);
sqlCSEditTbl.itemsProperty().setValue((ObservableList<SQLCalcScripts>) csSQLList);
return null;
}
};
// sqlCSEditTbl.itemsProperty().bind(task.valueProperty());
// sqlCSEditTbl.setItems(csEditCSList);
new Thread(task).start();
// Initialize table with columns
csEditID.setCellValueFactory(cellData -> cellData.getValue().calcScriptIDProperty().asObject());
csEditIndex.setCellValueFactory(cellData -> cellData.getValue().calcScriptIndexProperty().asObject());
csEditName.setCellValueFactory(cellData -> cellData.getValue().calcScriptNameProperty());
csEditServer.setCellValueFactory(cellData -> cellData.getValue().calcScriptServerProperty());
csEditApp.setCellValueFactory(cellData -> cellData.getValue().calcScriptAppProperty());
csEditGroup.setCellValueFactory(cellData -> cellData.getValue().calcScriptGroupProperty());
// TableView Calc Group ComboBox
ObservableList<String> csGroupList = FXCollections.observableArrayList("Supplement", "Wrapper", "Board Book");
csEditGroup.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), csGroupList));
csEditGroup.setOnEditCommit(
(TableColumn.CellEditEvent<SQLCalcScripts,String> cb) -> {
((SQLCalcScripts) cb.getTableView().getItems().get(
cb.getTablePosition().getRow()
)).setCalcScriptGroup(cb.getNewValue());
}
);
}
public void setScreenParent(ScreensController screenParent){
myController = screenParent;
}
#FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
#FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
#FXML // fx:id="sqlCSEditTbl"
private TableView<SQLCalcScripts> sqlCSEditTbl; // Value injected by FXMLLoader
#FXML // fx:id="csEditGroup"
private TableColumn<SQLCalcScripts, String> csEditGroup; // Value injected by FXMLLoader
#FXML // fx:id="csEditExitBtn"
private Button csEditExitBtn; // Value injected by FXMLLoader
#FXML // fx:id="csEditServer"
private TableColumn<SQLCalcScripts, String> csEditServer; // Value injected by FXMLLoader
#FXML // fx:id="csEditID"
private TableColumn<SQLCalcScripts, Integer> csEditID; // Value injected by FXMLLoader
#FXML // fx:id="csEditIndex"
private TableColumn<SQLCalcScripts, Integer> csEditIndex; // Value injected by FXMLLoader
#FXML // fx:id="csEditOkBtn"
private Button csEditOkBtn; // Value injected by FXMLLoader
#FXML // fx:id="csEditApp"
private TableColumn<SQLCalcScripts, String> csEditApp; // Value injected by FXMLLoader
#FXML // fx:id="csEditName"
private TableColumn<SQLCalcScripts, String> csEditName; // Value injected by FXMLLoader
#FXML
private void goToCSInt(ActionEvent event){
myController.setScreen(ScreensFramework.calcScriptInterfaceID);
}
// #FXML
// private void createTbl(ActionEvent event) {
// sqlCSEditTbl.setItems(csEditCSList);
// }
}
ControlledScreen class Code:
package sample;
/**
* Created by jdsmith on 4/21/2016.
*/
public interface ControlledScreen {
//This method will allow the injection of the Parent ScreenPane
public void setScreenParent(ScreensController screenPage);
}
ScreensController class Code:
package essapp;
import java.util.HashMap;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;
/**
* Created by jdsmith on 1/7/2016.
*/
public class ScreensController extends StackPane {
//Holds the screens to be displayed
private HashMap<String, Node> screens = new HashMap<>();
public ScreensController() {
super();
}
//Add the screen to the collection
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
//Returns the Node with the appropriate name
public Node getScreen(String name) {
return screens.get(name);
}
//Loads the fxml file, add the screen to the screens collection and
//finally injects the screenPane to the controller.
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenControler = ((ControlledScreen) myLoader.getController());
myScreenControler.setScreenParent(this);
addScreen(name, loadScreen);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}
//This method tries to displayed the screen with a predefined name.
//First it makes sure the screen has been already loaded. Then if there is more than
//one screen the new screen is been added second, and then the current screen is removed.
// If there isn't any screen being displayed, the new screen is just added to the root.
public boolean setScreen(final String name) {
if (screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
if (!getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
getChildren().remove(0); //remove the displayed screen
getChildren().add(0, screens.get(name)); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(800), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
setOpacity(0.0);
getChildren().add(screens.get(name)); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}
/*Node screenToRemove;
if(screens.get(name) != null){ //screen loaded
if(!getChildren().isEmpty()){ //if there is more than one screen
getChildren().add(0, screens.get(name)); //add the screen
screenToRemove = getChildren().get(1);
getChildren().remove(1); //remove the displayed screen
}else{
getChildren().add(screens.get(name)); //no one else been displayed, then just show
}
return true;
}else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}*/
}
//This method will remove the screen with the given name from the collection of screens
public boolean unloadScreen(String name) {
if (screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
ScreensFramework Main App Code:
package essapp;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class ScreensFramework extends Application {
public static String mainInterfaceID = "main";
public static String mainInterfaceFile = "mainInterface.fxml";
public static String msaInterfaceID = "msa";
public static String msaInterfaceFile = "msaInterface.fxml";
public static String creditRatingInterfaceID = "credit";
public static String creditRatingInterfaceFile = "creditRatingInterface.fxml";
public static String calcScriptEditID = "csEdit";
public static String calcScriptEditFile = "csEditInterface.fxml";
public static String calcScriptInterfaceID = "calc";
public static String calcScriptInterfaceFile = "calcScriptInterface.fxml";
public static String subVarInterfaceID = "subvar";
public static String subVarInterfaceFile = "subVarInterface.fxml";
#Override
public void start(Stage primaryStage) {
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(ScreensFramework.mainInterfaceID, ScreensFramework.mainInterfaceFile);
mainContainer.loadScreen(ScreensFramework.calcScriptInterfaceID, ScreensFramework.calcScriptInterfaceFile);
mainContainer.loadScreen(ScreensFramework.calcScriptEditID, ScreensFramework.calcScriptEditFile);
mainContainer.loadScreen(ScreensFramework.subVarInterfaceID, ScreensFramework.subVarInterfaceFile);
mainContainer.loadScreen(ScreensFramework.msaInterfaceID, ScreensFramework.msaInterfaceFile);
mainContainer.loadScreen(ScreensFramework.creditRatingInterfaceID, ScreensFramework.creditRatingInterfaceFile);
mainContainer.setScreen(ScreensFramework.mainInterfaceID);
mainContainer.prefHeightProperty().bind(primaryStage.heightProperty());
mainContainer.prefWidthProperty().bind(primaryStage.widthProperty());
mainContainer.setCenterShape(true);
mainContainer.setScaleShape(true);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
primaryStage.setWidth(bounds.getWidth());
primaryStage.setHeight(bounds.getHeight());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
When you call
sqlCSEditTbl.itemsProperty().setValue(...);
you are updating the UI (by updating the items displayed in the table). Like (almost?) all UI toolkits, JavaFX is single-threaded: updates to the UI can only happen on the FX Application Thread. Doing this in the Task, which is being executed on a background thread, will throw a IllegalStateException; so your call method never completes and you never see the update to the table.
The usual way to do this is to return the data from your call method:
Task<List<SQLCalcScripts>> task = new Task<List<SQLCalcScripts>>() {
#Override
public List<SQLCalcScripts> call() throws Exception {
List<SQLCalcScripts> data = /* get data.... */ ;
return data;
}
};
when the task completes, the value property is set to the value returned from the call method, so you can now do:
task.setOnSucceeded(e -> sqlCSEditTbl.getItems().setAll(task.getValue()));
It's probably a good idea to log any exceptions that occur with
task.setOnFailed(e -> task.getException().printStackTrace());
Then as before launch the task with
new Thread(task).start();

How to switch work spaces in JavaFX

I want to create several work spaces which can be switched with toggle buttons. I created this example
package menunavigation;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class MenuNavigation extends Application
{
#Override
public void start(Stage primaryStage)
{
final VBox vbox = new VBox();
MenuBar menuBar = new MenuBar();
// --- Menu File
Menu menuFile = new Menu("File");
// --- Menu Edit
Menu menuEdit = new Menu("Edit");
// --- Menu View
Menu menuView = new Menu("View");
menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
// buttons
String pillButtonCss = MenuNavigation.class.getResource("PillButton.css").toExternalForm();
// create 3 toggle buttons and a toogle group for them
ToggleButton tb1 = new ToggleButton("Left Button");
tb1.setId("pill-left");
ToggleButton tb2 = new ToggleButton("Center Button");
tb2.setId("pill-center");
ToggleButton tb3 = new ToggleButton("Right Button");
tb3.setId("pill-right");
final ToggleGroup group = new ToggleGroup();
tb1.setToggleGroup(group);
tb2.setToggleGroup(group);
tb3.setToggleGroup(group);
// select the first button to start with
group.selectToggle(tb1);
final Rectangle rect1 = new Rectangle(300, 300);
rect1.setFill(Color.ALICEBLUE);
final Rectangle rect2 = new Rectangle(300, 300);
rect2.setFill(Color.AQUA);
final Rectangle rect3 = new Rectangle(300, 300);
rect3.setFill(Color.AZURE);
tb1.setUserData(rect1);
tb2.setUserData(rect2);
tb3.setUserData(rect3);
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
{
#Override
public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle)
{
if (new_toggle == null)
{
//rect.setFill(Color.WHITE);
}
else
{
//rect.setFill((Color) group.getSelectedToggle().getUserData());
vbox.getChildren().setAll((Node) group.getSelectedToggle().getUserData());
}
}
});
HBox hBox = new HBox();
hBox.getChildren().addAll(tb1, tb2, tb3);
hBox.setPadding(new Insets(10, 10, 10, 10));
hBox.getStylesheets().add(pillButtonCss);
// end buttons
vbox.getChildren().addAll(menuBar, hBox, new Text("Test Space"));
StackPane root = new StackPane();
root.getChildren().add(vbox);
Scene scene = new Scene(root, 800, 850);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
This is the visual result:
When I press the second button I get this:
I want to use the toggle buttons to create different work spaces on which I want to place one main BorderPane or GridPane in which I want to insert many other components. Can you help me to get this result.
Is there a reason to not use a TabPane?
Edit:
Replace:
vbox.getChildren().setAll((Node) group.getSelectedToggle().getUserData());
With:
vbox.getChildren().set(2,(Node) group.getSelectedToggle().getUserData());
to show the rectangle instead of the Text.
This replaces the node with index 2 (the text) of your vbox with the node from ToggleButtons UserData (instead of replacing all elements in your current code).

How to perform functions on the stage in JavaFX's controller file

this question contains the code for my earlier question
Main class
#Override
public void start(Stage mainStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLfile.fxml"));
Scene scene = new Scene(root);
scene.setFill(Color.TRANSPARENT);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
}
FXMLController class
#FXML
private void getAxisLoc(ActionEvent axis) {
Stage stage;
stage = (Stage) root.getScene().getWindow();
int locX;
locX = (int) stage.getX();
int locY;
locY = (int) stage.getY();
}
The exception is fired here:
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:279)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
... 48 more
Caused by: java.lang.NullPointerException
at myJavaFile.FXMLfileController.getAxisLoc(FXMLfileController.java:112)
... 58 more`
Blindly, I guess that the NullPointerExeption is fired here:
stage = (Stage) root.getScene().getWindow();
If so, make sure that you added fx:id="root" in the root pane tag .
example (FXML):
<BorderPane fx:id="root" xmlns:fx="http://javafx.com/fxml" fx:controller="YourController">
and reference it in your controller class:
#FXML
Parent root;
SSCCE
Sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" fx:id="root" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="SampleController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>
SampleController.java
public class SampleController implements Initializable {
#FXML
private Label label;
#FXML
private Pane root;
#FXML
private void handleButtonAction(ActionEvent event) {
Stage stage = (Stage) root.getScene().getWindow();
//you can use label instead of root.
//Stage stage= (Stage) label.getScence().getWindow();
stage.close();
}
#Override
public void initialize(URL url, ResourceBundle rb) { //TODO }
}
App.java
public class App extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) { launch(args); }
}

JavaFX 2.0 Table with multiline table header

Is it possible to make javaFX 2.0 table with multiline header?
All the examples, which i have found on the web, have tables, where columnt header width = its text size, without wraping. The exaple of what i have, and what i need is shown on a screen:
Found a solution without using labels. In Scene Builder 8.3.0 (Gluon) , JavaFX 8 , a button appears on mouse hover, just right of the Text field, where a multi - line can be chosen from the menu.
This results in a following XML code:
<TableColumn fx:id="prodDisc" editable="false" prefWidth="50.0" text="Prod
Disc" />
I came up with the following function:
private void makeHeaderWrappable(TableColumn col) {
Label label = new Label(col.getText());
label.setStyle("-fx-padding: 8px;");
label.setWrapText(true);
label.setAlignment(Pos.CENTER);
label.setTextAlignment(TextAlignment.CENTER);
StackPane stack = new StackPane();
stack.getChildren().add(label);
stack.prefWidthProperty().bind(col.widthProperty().subtract(5));
label.prefWidthProperty().bind(stack.prefWidthProperty());
col.setGraphic(stack);
}
A complete executable example is in this gist (requires the 2.2 developer preview as a minimum).
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class TableWrappedHeaders extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
TableColumn firstNameCol = new TableColumn("First Name (which is a really long name)");
makeHeaderWrappable(firstNameCol);
firstNameCol.setPrefWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>("firstName"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setPrefWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>("lastName"));
TableView table = new TableView();
table.getColumns().addAll(firstNameCol, lastNameCol);
table.setItems(FXCollections.observableArrayList(
new Person("Jacob", "Smith"),
new Person("Isabella", "Johnson"),
new Person("Ethan", "Williams")
));
table.setPrefSize(250, 200);
Pane layout = new VBox(10);
layout.setStyle("-fx-padding: 10;");
layout.getChildren().addAll(table);
stage.setScene(new Scene(layout));
stage.show();
}
private void makeHeaderWrappable(TableColumn col) {
Label label = new Label(col.getText());
label.setStyle("-fx-padding: 8px;");
label.setWrapText(true);
label.setAlignment(Pos.CENTER);
label.setTextAlignment(TextAlignment.CENTER);
StackPane stack = new StackPane();
stack.getChildren().add(label);
stack.prefWidthProperty().bind(col.widthProperty().subtract(5));
label.prefWidthProperty().bind(stack.prefWidthProperty());
col.setText(null);
col.setGraphic(stack);
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private Person(String fName, String lName) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
}
public String getFirstName() { return firstName.get(); }
public void setFirstName(String fName) { firstName.set(fName); }
public String getLastName() { return lastName.get(); }
public void setLastName(String fName) { lastName.set(fName); }
}
}
There is probably a better way to do this, but the function above did at least work for me in my test case.
I thought this would be achievable with a simple css style, but I could not get it to work via css alone.
Is easier with a Label in the header graphic of the column:
Add a label in the column header graphic (if the column has some text as title delete it).
Set the label to allow Wrap Text
(Scene Builder -> go to Properties of the label and select Wrap Text or in Code -> label.setWrapText(true))
Set label width and height we wish
Note: is easier to do this in a FXML (with Scene Builder) than in code.
Example below:
public class TableColumnLongTextLabel extends Application {
#Override
public void start(Stage stage) {
TableView table = new TableView();
TableColumn tableColumnData1 = new TableColumn(),
tableColumnData2 = new TableColumn("Long Title without Text Wrap");
tableColumnData1.setCellValueFactory(new PropertyValueFactory<SomeStructure, String>("data1"));
tableColumnData2.setCellValueFactory(new PropertyValueFactory<SomeStructure, String>("data2"));
table.getColumns().addAll(tableColumnData1, tableColumnData2);
Label columnTitle = new Label("Long Title with Text Wrapped");
columnTitle.setPrefWidth(125);
columnTitle.setPrefHeight(50);
columnTitle.setWrapText(true);
columnTitle.setTextAlignment(TextAlignment.CENTER);
tableColumnData1.setGraphic(columnTitle);
table.setItems(FXCollections.observableArrayList(
new SomeStructure("Java", "FX", 1),
new SomeStructure("Java", "Swing", 0),
new SomeStructure("Java", "Sample", 2),
new SomeStructure("Some", "Other", 10)
));
Pane layout = new VBox(10);
layout.getChildren().addAll(table);
stage.setScene(new Scene(layout, 350, 350));
stage.show();
}
public static class SomeStructure {
private final SimpleStringProperty data1;
private final SimpleStringProperty data2;
private final SimpleIntegerProperty data3;
private SomeStructure(String data1, String data2, Integer data3) {
this.data1 = new SimpleStringProperty(data1);
this.data2 = new SimpleStringProperty(data2);
this.data3 = new SimpleIntegerProperty(data3);
}
public String getData1() {
return data1.get();
}
public void setData1(String data1) {
this.data1.set(data1);
}
public String getData2() {
return data2.get();
}
public void setData2(String data2) {
this.data2.set(data2);
}
public Integer getData3() {
return data3.get();
}
public void setData3(Integer data3) {
this.data3.set(data3);
}
}
public static void main(String[] args) {
launch(args);
}
}
Example using FXML (No code needed :) ):
<TableView prefHeight="251.0" prefWidth="556.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<columns>
<TableColumn editable="false" maxWidth="90.0" prefWidth="70.0" sortable="false" text="Player">
<columns>
<TableColumn editable="false" maxWidth="80.0" prefWidth="50.0" text="ID" />
<TableColumn editable="false" maxWidth="200.0" prefWidth="180.0" text="Name" />
</columns>
</TableColumn>
<TableColumn maxWidth="80.0" minWidth="50.0" prefWidth="60.0" text="Game" />
<TableColumn editable="false" maxWidth="160.0" minWidth="125.0" prefWidth="135.0" sortable="false" text="Team" visible="false" />
<TableColumn editable="false" maxWidth="160.0" minWidth="107.0" prefWidth="107.0" sortable="false">
<graphic>
<Label alignment="CENTER" text="Individual Points (Big Team)" textAlignment="CENTER" wrapText="true" />
</graphic>
</TableColumn>
<TableColumn editable="false" maxWidth="160.0" minWidth="99.0" prefWidth="102.0" sortable="false">
<graphic>
<Label alignment="CENTER" text="Team Points (Small Maps)" textAlignment="CENTER" wrapText="true" />
</graphic>
</TableColumn>
<TableColumn editable="false" maxWidth="116.0" minWidth="55.0" prefWidth="55.0" sortable="false">
<graphic>
<Label text="Total Points" textAlignment="CENTER" wrapText="true" />
</graphic>
</TableColumn>
</columns>
</TableView>
The easiest way to align header text is with CSS style, like this:
.table-view .column-header .label {
-fx-text-alignment: center;
}
Use new line escape sequence "\n" in header text string to split it into multiple lines.

How to create custom components in JavaFX 2.0 using FXML?

I can't seem to find any material on the subject. To give a more concrete example, let's say I want to create a simple component that combines a checkbox and a label. Then, populate a ListView with instances of this custom component.
UPDATE:
see my answer for complete code
UPDATE 2:
For an up-to-date tutorial, please, consult the official documentation. There was a lot of new stuff that was added in 2.2. Finally, the Introduction to FXML covers pretty much everything you need to know about FXML.
UPDATE 3:
Hendrik Ebbers made an extremely helpful blog post about custom UI controls.
Update: For an up-to-date tutorial, please, consult the official documentation. There was a lot of new stuff that was added in 2.2. Also, the Introduction to FXML covers pretty much everything you need to know about FXML. Finally, Hendrik Ebbers made an extremely helpful blog post about custom UI controls.
After a few days of looking around the API and reading through some docs (Intro to FXML, Getting started with FXML Property binding, Future of FXML) I've come up with a fairly sensible solution.
The least straight-forward piece of information I learned from this little experiment was that the instance of a controller (declared with fx:controller in FXML) is held by the FXMLLoader that loaded the FXML file... Worst of all, this important fact is only mentioned in one place in all the docs I saw:
a controller is generally only visible to the FXML loader that creates it
So, remember, in order to programmatically (from Java code) obtain a reference to the instance of a controller that was declared in FXML with fx:controller use FXMLLoader.getController() (refer to the implementation of the ChoiceCell class below for a complete example).
Another thing to note is that Property.bindBiderctional() will set the value of the calling property to the value of the property passed in as the argument. Given two boolean properties target (originally set to false) and source (initially set to true) calling target.bindBidirectional(source) will set the value of target to true. Obviously, any subsequent changes to either property will change the other property's value (target.set(false) will cause the value of source to be set to false):
BooleanProperty target = new SimpleBooleanProperty();//value is false
BooleanProperty source = new SimpleBooleanProperty(true);//value is true
target.bindBidirectional(source);//target.get() will now return true
target.set(false);//both values are now false
source.set(true);//both values are now true
Anyway, here is the complete code that demonstrates how FXML and Java can work together (as well as a few other useful things)
Package structure:
com.example.javafx.choice
ChoiceCell.java
ChoiceController.java
ChoiceModel.java
ChoiceView.fxml
com.example.javafx.mvc
FxmlMvcPatternDemo.java
MainController.java
MainView.fxml
MainView.properties
FxmlMvcPatternDemo.java
package com.example.javafx.mvc;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FxmlMvcPatternDemo extends Application
{
public static void main(String[] args) throws ClassNotFoundException
{
Application.launch(FxmlMvcPatternDemo.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load
(
FxmlMvcPatternDemo.class.getResource("MainView.fxml"),
ResourceBundle.getBundle(FxmlMvcPatternDemo.class.getPackage().getName()+".MainView")/*properties file*/
);
stage.setScene(new Scene(root));
stage.show();
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.mvc.MainController"
prefWidth="300"
prefHeight="400"
fillWidth="false"
>
<children>
<Label text="%title" />
<ListView fx:id="choicesView" />
<Button text="Force Change" onAction="#handleForceChange" />
</children>
</VBox>
MainView.properties
title=JavaFX 2.0 FXML MVC demo
MainController.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceCell;
import com.example.javafx.choice.ChoiceModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
public class MainController implements Initializable
{
#FXML
private ListView<ChoiceModel> choicesView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
choicesView.setCellFactory(new Callback<ListView<ChoiceModel>, ListCell<ChoiceModel>>()
{
public ListCell<ChoiceModel> call(ListView<ChoiceModel> p)
{
return new ChoiceCell();
}
});
choicesView.setItems(FXCollections.observableArrayList
(
new ChoiceModel("Tiger", true),
new ChoiceModel("Shark", false),
new ChoiceModel("Bear", false),
new ChoiceModel("Wolf", true)
));
}
#FXML
private void handleForceChange(ActionEvent event)
{
if(choicesView != null && choicesView.getItems().size() > 0)
{
boolean isSelected = choicesView.getItems().get(0).isSelected();
choicesView.getItems().get(0).setSelected(!isSelected);
}
}
}
ChoiceView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.choice.ChoiceController"
>
<children>
<CheckBox fx:id="isSelectedView" />
<Label fx:id="labelView" />
</children>
</HBox>
ChoiceController.java
package com.example.javafx.choice;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
public class ChoiceController
{
private final ChangeListener<String> LABEL_CHANGE_LISTENER = new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> property, String oldValue, String newValue)
{
updateLabelView(newValue);
}
};
private final ChangeListener<Boolean> IS_SELECTED_CHANGE_LISTENER = new ChangeListener<Boolean>()
{
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue)
{
updateIsSelectedView(newValue);
}
};
#FXML
private Label labelView;
#FXML
private CheckBox isSelectedView;
private ChoiceModel model;
public ChoiceModel getModel()
{
return model;
}
public void setModel(ChoiceModel model)
{
if(this.model != null)
removeModelListeners();
this.model = model;
setupModelListeners();
updateView();
}
private void removeModelListeners()
{
model.labelProperty().removeListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().removeListener(IS_SELECTED_CHANGE_LISTENER);
isSelectedView.selectedProperty().unbindBidirectional(model.isSelectedProperty())
}
private void setupModelListeners()
{
model.labelProperty().addListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().addListener(IS_SELECTED_CHANGE_LISTENER);
isSelectedView.selectedProperty().bindBidirectional(model.isSelectedProperty());
}
private void updateView()
{
updateLabelView();
updateIsSelectedView();
}
private void updateLabelView(){ updateLabelView(model.getLabel()); }
private void updateLabelView(String newValue)
{
labelView.setText(newValue);
}
private void updateIsSelectedView(){ updateIsSelectedView(model.isSelected()); }
private void updateIsSelectedView(boolean newValue)
{
isSelectedView.setSelected(newValue);
}
}
ChoiceModel.java
package com.example.javafx.choice;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ChoiceModel
{
private final StringProperty label;
private final BooleanProperty isSelected;
public ChoiceModel()
{
this(null, false);
}
public ChoiceModel(String label)
{
this(label, false);
}
public ChoiceModel(String label, boolean isSelected)
{
this.label = new SimpleStringProperty(label);
this.isSelected = new SimpleBooleanProperty(isSelected);
}
public String getLabel(){ return label.get(); }
public void setLabel(String label){ this.label.set(label); }
public StringProperty labelProperty(){ return label; }
public boolean isSelected(){ return isSelected.get(); }
public void setSelected(boolean isSelected){ this.isSelected.set(isSelected); }
public BooleanProperty isSelectedProperty(){ return isSelected; }
}
ChoiceCell.java
package com.example.javafx.choice;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
public class ChoiceCell extends ListCell<ChoiceModel>
{
#Override
protected void updateItem(ChoiceModel model, boolean bln)
{
super.updateItem(model, bln);
if(model != null)
{
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try
{
Node root = (Node)fxmlLoader.load(location.openStream());
ChoiceController controller = (ChoiceController)fxmlLoader.getController();
controller.setModel(model);
setGraphic(root);
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe);
}
}
}
}
For JavaFx 2.1, You can create a custom FXML control component by this way:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import customcontrolexample.myCommponent.*?>
<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="customcontrolexample.FXML1Controller">
<children>
<MyComponent welcome="1234"/>
</children>
</VBox>
Component code:
MyComponent.java
package customcontrolexample.myCommponent;
import java.io.IOException;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.util.Callback;
public class MyComponent extends Pane {
private Node view;
private MyComponentController controller;
public MyComponent() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("myComponent.fxml"));
fxmlLoader.setControllerFactory(new Callback<Class<?>, Object>() {
#Override
public Object call(Class<?> param) {
return controller = new MyComponentController();
}
});
try {
view = (Node) fxmlLoader.load();
} catch (IOException ex) {
}
getChildren().add(view);
}
public void setWelcome(String str) {
controller.textField.setText(str);
}
public String getWelcome() {
return controller.textField.getText();
}
public StringProperty welcomeProperty() {
return controller.textField.textProperty();
}
}
MyComponentController.java
package customcontrolexample.myCommponent;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
public class MyComponentController implements Initializable {
int i = 0;
#FXML
TextField textField;
#FXML
protected void doSomething() {
textField.setText("The button was clicked #" + ++i);
}
#Override
public void initialize(URL location, ResourceBundle resources) {
textField.setText("Just click the button!");
}
}
myComponent.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="customcontrolexample.myCommponent.MyComponentController">
<children>
<TextField fx:id="textField" prefWidth="200.0" />
<Button mnemonicParsing="false" onAction="#doSomething" text="B" />
</children>
</VBox>
This code needs to check if there is no memory leak.
Quick answer is <fx:include> tag, however, you would need to set the ChoiceModel in the Controller class.
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="fxmltestinclude.ChoiceDemo"
>
<children>
**<fx:include source="Choice.fxml" />**
<ListView fx:id="choices" />
</children>
</VBox>
The introduction to fxml chapter on custom components
gave me the right hint. My intention was to combine a label a slider and a textfield to one custom LabeledValueSlider component.
Usage example:
see resources/fx of rc-dukes Self-Driving RC Car Java FX App
<LabeledValueSlider fx:id='cannyThreshold1' text="Canny threshold 1" blockIncrement="1" max="2000" min="0" value="20" format="\%.0f"/>
<LabeledValueSlider fx:id="cannyThreshold2" text="Canny threshold 2" blockIncrement="1" max="2000" min="0" value="50" format="\%.0f"/>
<LabeledValueSlider fx:id="lineDetectRho" text="LineDetect rho" blockIncrement="0.01" max="20" min="0" value="0.5" />
<LabeledValueSlider fx:id="lineDetectTheta" text="LineDetect theta" blockIncrement="0.01" max="5" min="-5" value="0.5" />
<LabeledValueSlider fx:id="lineDetectThreshold" text="LineDetect threshold" blockIncrement="1" max="200" min="0" value="20" format="\%.0f" />
<LabeledValueSlider fx:id="lineDetectMinLineLength" text="LineDetect minLineLength" blockIncrement="1" max="200" min="0" value="50" format="\%.0f"/>
<LabeledValueSlider fx:id="lineDetectMaxLineGap" text="LineDetect maxLineGap" blockIncrement="1" max="500" min="0" value="50" format="\%.0f"/>
FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
<fx:root type="javafx.scene.layout.HBox" xmlns:fx="http://javafx.com/fxml">
<padding>
<Insets left="10" right="10" />
</padding>
<Label fx:id='label' text="Label for Slider" minWidth="180"/>
<Slider fx:id='slider' blockIncrement="1" max="100" min="0" value="50" />
<TextField fx:id="textField" maxWidth="75"/>
</fx:root>
Component Source code
see LabeledValueSlider.java
package org.rcdukes.app;
import java.io.IOException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
/**
* a Slider with a Label and a value
*
* #author wf
*
*/
public class LabeledValueSlider extends HBox {
public static boolean debug=true;
protected static final Logger LOG = LoggerFactory
.getLogger(LabeledValueSlider.class);
#FXML
private Label label;
#FXML
private Slider slider;
#FXML
private TextField textField;
String format;
public String getFormat() {
return format;
}
public void setFormat(String format) {
textField.textProperty().bind(slider.valueProperty().asString(format));
this.format = format;
}
public double getBlockIncrement() {
return slider.getBlockIncrement();
}
public void setBlockIncrement(double value) {
slider.setBlockIncrement(value);
}
public double getMax() {
return slider.getMax();
}
public void setMax(double value) {
slider.setMax(value);
}
public double getMin() {
return slider.getMin();
}
public void setMin(double value) {
slider.setMin(value);
}
public double getValue() {
return slider.getValue();
}
public void setValue(double value) {
slider.setValue(value);
}
public String getText() {
return label.getText();
}
public void setText(String pLabelText) {
label.setText(pLabelText);
}
public URL getResource(String path) {
return getClass().getClassLoader().getResource(path);
}
/**
* construct me
* see https://docs.oracle.com/javase/9/docs/api/javafx/fxml/doc-files/introduction_to_fxml.html#custom_components
*/
public LabeledValueSlider() {
FXMLLoader fxmlLoader = new FXMLLoader(
getResource("fx/labeledvalueslider.fxml"));
try {
// let's load the HBox - fxmlLoader doesn't know anything about us yet
fxmlLoader.setController(this);
fxmlLoader.setRoot(this);
Object loaded = fxmlLoader.load();
Object root=fxmlLoader.getRoot();
if (debug) {
String msg=String.format("%s loaded for root %s", loaded.getClass().getName(),root.getClass().getName());
LOG.info(msg);
}
textField.setAlignment(Pos.CENTER_RIGHT);
if (format == null)
setFormat("%.2f");
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
}

Resources