java fx add element an ScroolPane - javafx

I 've searched and have not found an answer.
I have a scroll , a button and a textarea. when i press the button, i take the value in the textarea, then I want the text to be put at the top right in scrool , if ipress one more time to go under and so on. example
hello guys
this is my label
text area button
this is my fxml file
<AnchorPane id="AnchorPane" prefHeight="392.0" prefWidth="357.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="indixischat.ChatController">
<children>
<Pane id="title" layoutX="14.0" layoutY="14.0" prefHeight="60.0" prefWidth="333.0" />
<TextField fx:id="text" layoutX="14.0" layoutY="362.0" prefHeight="17.0" prefWidth="299.0" />
<Button fx:id="sendMessage" onAction="#sendMessage" layoutX="318.0" layoutY="365.0" mnemonicParsing="false" prefHeight="11.0" prefWidth="29.0" text="Button" />
<ScrollPane fx:id="scroll" layoutX="14.0" layoutY="44.0" prefHeight="319.0" prefWidth="339.0">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="412.0" prefWidth="326.0" />
</content>
</ScrollPane>

You can use a VBox as a container for the texts in the ScrollPane. Then on each Button click you create a new TextField and add that to the VBox:
public class Test extends Application {
#Override
public void start(Stage primaryStage) {
TextField txtInput = new TextField();
VBox boxTextFields = new VBox();
boxTextFields.setAlignment(Pos.TOP_RIGHT);
boxTextFields.setFillWidth(false);
ScrollPane scrollPane = new ScrollPane(boxTextFields);
scrollPane.setFitToWidth(true);
Button button = new Button();
button.setOnAction(e -> boxTextFields.getChildren().add(new TextField(txtInput.getText())));
VBox root = new VBox(textField, button, scrollPane);
root.setAlignment(Pos.TOP_CENTER);
primaryStage.setScene(new Scene(root, 300, 300));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Related

My GUI will not show up even when the program is running. t

[enter image description here][1]Here is the Driver , The program will run with no errors but the gui will not show up at all. I am a noob to FX and i am just trying to get it to work.
public class Vacation extends Application {
private Stage stage;
#Override
public void start(Stage stage) throws Exception {
this.stage = stage;
try{
FXMLLoader loader = new
FXMLLoader(getClass().getResource("Vacation.fxml"));
AnchorPane pane = loader.load();
MainControler mainController = loader.getController();
Scene scene = new Scene(pane, 640, 450);
stage.setScene(scene);
stage.show();
}catch(IOException e){
}
}
public static void main(String[] args) {
launch(args);
}
}
Here is the FXML.
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.141" fx:controller="Application.MainControler">
<children>
<AnchorPane layoutX="9.0" layoutY="8.0" prefHeight="131.0" prefWidth="572.0" style="-fx-background-color: #333333;">
<children>
<ImageView fitHeight="106.0" fitWidth="470.0" layoutX="51.0" layoutY="13.0">
<image>
<Image url="#../../../../../Desktop/FxPics/dc3.jpg" />
</image>
</ImageView>
<Button fx:id="DC" layoutX="229.0" layoutY="53.0" mnemonicParsing="false" onAction="#DCbuttonPpess" text="Devils CourtHouse" textFill="#ee0707" />
</children>
</AnchorPane>
<AnchorPane layoutX="9.0" layoutY="149.0" prefHeight="131.0" prefWidth="572.0" style="-fx-background-color: #333333;">
<children>
<ImageView fitHeight="100.0" fitWidth="476.0" layoutX="49.0" layoutY="17.0">
<image>
<Image url="#../../../../../Desktop/FxPics/reef.jpg" />
</image>
</ImageView>
<Button fx:id="STB" layoutX="226.0" layoutY="55.0" mnemonicParsing="false" onAction="#STBbuttonPress" text="Scuba The Bahamas" textFill="#01d3f8" />
</children>
</AnchorPane>
<AnchorPane layoutX="9.0" layoutY="295.0" prefHeight="131.0" prefWidth="572.0" style="-fx-background-color: #333333;">
<children>
<ImageView fitHeight="100.0" fitWidth="488.0" layoutX="42.0" layoutY="16.0">
<image>
<Image url="#../../../../../Desktop/FxPics/SD2.jpg" />
</image>
</ImageView>
<Button fx:id="SDC" layoutX="230.0" layoutY="53.0" mnemonicParsing="false" onAction="#SDCButtonPress" text="Sky Dive Colorado" textFill="#ffa616" />
</children>
</AnchorPane>
<AnchorPane layoutX="9.0" layoutY="445.0" prefHeight="131.0" prefWidth="572.0" style="-fx-background-color: #333333;">
<children>
<ImageView fitHeight="106.0" fitWidth="488.0" layoutX="42.0" layoutY="13.0">
<image>
<Image url="#../../../../../Desktop/FxPics/c3.jpg" />
</image>
</ImageView>
<Button fx:id="BC" layoutX="248.0" layoutY="54.0" mnemonicParsing="false" onAction="#BCButtonpress" text="Baron Cliffs" textFill="#543801" />
</children>
</AnchorPane>
and here is the Controller.
public class MainControler implements Initializable {
#FXML
private Button DC;
#FXML
private Button STB;
#FXML
private Button SDC;
#FXML
private Button BC;
#FXML public void BCButtonpress(ActionEvent event) {
try{
FXMLLoader bcLoader = new
FXMLLoader(getClass().getResource("BaronCliff.fxml"));
Parent root1 = (Parent) bcLoader.load();
Stage bc = new Stage();
bc.setTitle("Baron Cliff");
bc.setScene(new Scene(root1));
bc.show();
}catch (IOException e){
System.out.println("Cant Load new Window.");
}
}
#FXML public void DCbuttonpress(ActionEvent event) {
try{
FXMLLoader bcLoader = new
FXMLLoader(getClass().getResource("DevilsCourthouse.fxml"));
Parent root1 = (Parent) bcLoader.load();
Stage bc = new Stage();
bc.setTitle("Devils Courthouse");
bc.setScene(new Scene(root1));
bc.show();
}catch (IOException e){
System.out.println("Cant Load new Window.");
}
}
#FXML public void STBbuttonPress(ActionEvent event) {
try{
FXMLLoader bcLoader = new
FXMLLoader(getClass().getResource("Scuba.fxml"));
Parent root1 = (Parent) bcLoader.load();
Stage bc = new Stage();
bc.setTitle("Scuba the Bahamas");
bc.setScene(new Scene(root1));
bc.show();
}catch (Exception e){
System.out.println("Cant Load new Window.");
}
}
#FXML public void SDC(ActionEvent event) {
try{
FXMLLoader bcLoader = new
FXMLLoader(getClass().getResource("Skydive.fxml"));
Parent root1 = (Parent) bcLoader.load();
Stage bc = new Stage();
bc.setTitle("Skydive Colorado");
bc.setScene(new Scene(root1));
bc.show();
}catch (Exception e){
System.out.println("Cant Load new Window.");
}
}
Thanks in advance for any help, I finally broke down and decided to post this, i could not find anyone with my problem probably something minor but i have no one with fresh eyes to really give it a look. apologies.
After putting in the e.printStackTrace(); in the catch block I got a list of exceptions.
javafx.fxml.LoadException: Error resolving
onAction='#DCbuttonPpess', either the event handler is
not in the Namespace or there is an error in the script.
file:/C:/Users/Kalamar/Documents/NetBeansProjects/Vacation/di
st/run201542084/Vacation.jar!/Application/Vacation.fxml:17
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2597)
at javafx.fxml.FXMLLoader.access$100(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$Element.processEventHandlerAttributes(FXMLLoader.java:610)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:770)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2823)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2532)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at Application.Vacation.start(Vacation.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
here is the typo fixed.
<Button fx:id="DC" layoutX="229.0" layoutY="53.0" mnemonicParsing="false"
onAction="#DCbuttonpress" text="Devils CourtHouse" textFill="#ee0707"
/>enter
here is the exception after running after the fix.
Executing C:\Users\Kalamar\Documen
ts\NetBeansProjects\Vacation\dist \run1238622098\Vacation
.jar using platform C:\Program Files\Java\jdk1.8.0_151\jre/bin/java
javafx.fxml.LoadException: Error resolving onAction='#DCbuttonpress',
either the event handler is not in the Namespace or there is an
error in the script
file:/C:/Users/Kalamar/Documents/NetBeansProjects/Vacation/d
ist/run1238622098/V acation.jar!/Application/Vacation.fxml:17
The stack trace:
javafx.fxml.LoadException: Error resolving
onAction='#DCbuttonPpess', either the event handler is
not in the Namespace or there is an error in the script.
file:/C:/Users/Kalamar/Documents/NetBeansProjects/Vacation/di
st/run201542084/Vacation.jar!/Application/Vacation.fxml:17
Indicates that there is a problem with the onAction handler specified at line 17 of the Vacation.fxml file. That line is:
<Button fx:id="DC" ... onAction="#DCbuttonPpess" ... />
There is a clear typo in the onAction attribute: the method defined in the controller class is
#FXML public void DCbuttonpress(ActionEvent event) {
/* ... */
}
So the FXML should be
<Button fx:id="DC" ... onAction="#DCbuttonpress" ... />

How can I click a GridPane Cell and have it perform an action?

I'm new to JavaFX (Java for that matter) and I want to be able to click a GridPane and have it display my room attributes in a side-panel(or to console at this point). I've managed to setup a mouse event but I don't think it's the right tool for the job. When I click anywhere in the grid, it returns "null" and won't give me the cell coordinates(maybe there's better or more useful info to gather here?).
I'm using Scene Builder as well.
Controller Class
import Data.Area;
import Model.Grid;
import Model.TileSet;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Controller {
InputStream rinput = getClass().getResourceAsStream("/red.png");
Image red = new Image(rinput);
ImageView redimg = new ImageView(red);
InputStream binput = getClass().getResourceAsStream("/black.png");
Image black = new Image(binput);
InputStream pinput = getClass().getResourceAsStream("/pink.png");
Image pink = new Image(binput);
#FXML
public GridPane gridmane;
public void genSmall(ActionEvent actionEvent) throws IOException {
Grid grid = new Grid(new Area(40, 40));
grid.getPathfinder().shufflePartitions();
grid.getPathfinder().fillPartitions();
grid.getPathfinder().generateHallways();
grid.getPathfinder().placeWalls();
importGrid(gridmane, grid);
gridmane.getScene().getWindow().sizeToScene();
}
public void genMed(ActionEvent actionEvent) throws IOException {
Grid grid = new Grid(new Area(60, 60));
grid.getPathfinder().shufflePartitions();
grid.getPathfinder().fillPartitions();
grid.getPathfinder().generateHallways();
grid.getPathfinder().placeWalls();
gridmane.getScene().getWindow().sizeToScene();
gridmane.getScene().getWindow().setHeight(600);
gridmane.getScene().getWindow().setWidth(600);
importGrid(gridmane, grid);
}
public void genLarge(ActionEvent actionEvent) throws IOException {
Grid grid = new Grid(new Area(80, 80));
grid.getPathfinder().shufflePartitions();
grid.getPathfinder().fillPartitions();
grid.getPathfinder().generateHallways();
grid.getPathfinder().placeWalls();
gridmane.getScene().getWindow().sizeToScene();
gridmane.getScene().getWindow().setHeight(800);
gridmane.getScene().getWindow().setWidth(800);
importGrid(gridmane, grid);
}
private void importGrid(GridPane gridPane, Grid grid) {
gridPane.getChildren().clear(); // remove old children
for (int i = 0; i < grid.getSize().height; i++) {
for (int j = 0; j < grid.getSize().width; j++) {
if (grid.getContent()[j + (i * grid.getSize().width)] == TileSet.floorTile) {
changeSquare(gridPane, i, j, Color.WHITE, red);
}
else if (grid.getContent()[j + (i * grid.getSize().width)] == TileSet.wallTile) {
changeSquare(gridPane, i, j, Color.GRAY, black);
}
else {
changeSquare(gridPane, i, j, Color.BLACK, pink);
}
}
}
}
private void changeSquare(GridPane gridPane, int xCoordinate, int yCoordinate, Color color, Image image) {
Rectangle rect = new Rectangle();
ImageView fimage = new ImageView(image);
rect.setStroke(Color.BLACK);
rect.setFill(color);
rect.setWidth(10);
rect.setHeight(10);
gridPane.add(fimage, xCoordinate, yCoordinate);
}
public void clickGrid(javafx.scene.input.MouseEvent event) {
Node source = (Node)event.getSource() ;
Integer colIndex = gridmane.getColumnIndex(source);
Integer rowIndex = gridmane.getRowIndex(source);
System.out.println("Mouse clicked cell: " + colIndex + "And: " + rowIndex);
}
}
Main Class
public class Main extends Application {
Stage stage = new Stage();
int val = 40;
#Override
public void start(Stage primaryStage) throws Exception {
this.stage = primaryStage;
setVal(val);
}
public static void main(String[] args) {
launch(args);
}
public void setVal(int i) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/view.fxml"));
stage.setTitle("Dungeon Generator");
stage.setScene(new Scene(root, 450, 450));
//primaryStage.setResizable(false);
stage.sizeToScene();
stage.show();
}
}
FXML File
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.image.Image?>
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="258.0" prefWidth="332.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
<children>
<MenuBar>
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
<children>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#genSmall" prefHeight="27.0" prefWidth="64.0" text="Small" HBox.hgrow="ALWAYS">
<HBox.margin>
<Insets left="20.0" />
</HBox.margin>
</Button>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#genMed" text="Medium" HBox.hgrow="ALWAYS">
<HBox.margin>
<Insets left="20.0" />
</HBox.margin>
</Button>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#genLarge" prefHeight="27.0" prefWidth="66.0" text="Large" HBox.hgrow="ALWAYS">
<HBox.margin>
<Insets left="20.0" />
</HBox.margin>
</Button>
</children>
</HBox>
<StackPane>
<children>
<GridPane fx:id="gridmane" maxHeight="-Infinity" maxWidth="-Infinity" onMouseClicked="#clickGrid" VBox.vgrow="NEVER" />
</children>
</StackPane>
</children>
</VBox>
Since you register the event handler at the GridPane, the source of the event is the GridPane itself. You did not set the row/column index for the GridPane and it wouldn't contain any useful information.
In this case you need to get the node that was actually clicked from the MouseEvent:
public void clickGrid(javafx.scene.input.MouseEvent event) {
Node clickedNode = event.getPickResult().getIntersectedNode();
if (clickedNode != gridmane) {
// click on descendant node
Integer colIndex = GridPane.getColumnIndex(clickedNode);
Integer rowIndex = GridPane.getRowIndex(clickedNode);
System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
}
}
In this case the code works like this since the children of your GridPane don't have children of their own that could be the intersected node.
If you want to add children that could have children of their own you need to go up through the node hierarchy until you find a child of the GridPane:
if (clickedNode != gridmane) {
// click on descendant node
Node parent = clickedNode.getParent();
while (parent != gridmane) {
clickedNode = parent;
parent = clickedNode.getParent();
}
Integer colIndex = GridPane.getColumnIndex(clickedNode);
Integer rowIndex = GridPane.getRowIndex(clickedNode);
System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
}

Javafx: How can I code the calculation to get results when I click the button?

package javafx_tipcalc;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.text.NumberFormat;
public class JavaFX_TipCalc extends Application {
// declare interface controls
// declare labels
Label titleLabel, checkAmtLabel, tipPercentLabel, splitLabel;
Label tipAmtLabel, totalLabel, amtPerPersonLabel;
// declare text fields
TextField checkAmtText, tipAmtText, totalText, amtPerPersonText;
// declare a slider
Slider tipPercentSlider;
// declare a choice box
ChoiceBox splitChoiceBox;
// declare a button
Button calcTipButton;
// declare currency and percent formatter
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat persent = NumberFormat.getCurrencyInstance();
// declare a grid pane (8 rows and 2 columns)
GridPane grid;
#Override
public void start(Stage primaryStage) {
// instantiate labels and their properties
titleLabel = new Label("Tip Calculator");
titleLabel.setMaxWidth(Double.MAX_VALUE);
titleLabel.setAlignment(Pos.CENTER);
checkAmtLabel = new Label("Check Amount");
checkAmtLabel.setMaxWidth(Double.MAX_VALUE);
checkAmtLabel.setAlignment(Pos.CENTER_RIGHT);
tipPercentLabel = new Label("Tip Percent: 15%");
tipPercentLabel.setMaxWidth(Double.MAX_VALUE);
tipPercentLabel.setAlignment(Pos.CENTER_RIGHT);
splitLabel = new Label("Split");
splitLabel.setMaxWidth(Double.MAX_VALUE);
splitLabel.setAlignment(Pos.CENTER_RIGHT);
tipAmtLabel = new Label("Tip Amount");
tipAmtLabel.setMaxWidth(Double.MAX_VALUE);
tipAmtLabel.setAlignment(Pos.CENTER_RIGHT);
totalLabel = new Label("Total");
totalLabel.setMaxWidth(Double.MAX_VALUE);
totalLabel.setAlignment(Pos.CENTER_RIGHT);
amtPerPersonLabel = new Label("Amount per Person");
amtPerPersonLabel.setMaxWidth(Double.MAX_VALUE);
amtPerPersonLabel.setAlignment(Pos.CENTER_RIGHT);
// instantiate text fileds and their properties
double textFieldWidth = 100;
checkAmtText = new TextField();
checkAmtText.setOnMouseClicked(e -> ResetFields());
checkAmtText.setPrefWidth(textFieldWidth);
checkAmtText.setAlignment(Pos.CENTER_RIGHT);
tipAmtText = new TextField();
tipAmtText.setFocusTraversable(false);
tipAmtText.setPrefWidth(textFieldWidth);
tipAmtText.setAlignment(Pos.CENTER_RIGHT);
tipAmtText.setEditable(false);
totalText = new TextField();
totalText.setFocusTraversable(false);
totalText.setPrefWidth(textFieldWidth);
totalText.setAlignment(Pos.CENTER_RIGHT);
totalText.setEditable(false);
amtPerPersonText = new TextField();
amtPerPersonText.setFocusTraversable(false);
amtPerPersonText.setPrefWidth(textFieldWidth);
amtPerPersonText.setAlignment(Pos.CENTER_RIGHT);
amtPerPersonText.setEditable(false);
// instantiate a slider and its properties
tipPercentSlider = new Slider();
tipPercentSlider.setPrefWidth(10);
tipPercentSlider = new javafx.scene.control.Slider();
tipPercentSlider.setPrefWidth(150);
tipPercentSlider.setMin(0);
tipPercentSlider.setMax(25);
tipPercentSlider.setMajorTickUnit(5);
tipPercentSlider.setMinorTickCount(1);
tipPercentSlider.setBlockIncrement(1);
tipPercentSlider.setShowTickLabels(true);
tipPercentSlider.setShowTickMarks(true);
tipPercentSlider.setSnapToTicks(true);
tipPercentSlider.setValue(15);
tipPercentSlider.setOrientation(Orientation.HORIZONTAL);
tipPercentSlider.valueProperty().addListener(
(observable, oldvalue, newvalue) ->
{
tipPercentLabel.setText(String.format("Tip Percent:
%2d%s",newvalue.intValue(),"%"));
} );
// instantiate a choice box and its properties
splitChoiceBox = new ChoiceBox();
splitChoiceBox.getItems().addAll("1 Way", "2 Ways", "3 Ways", "4
Ways", "5 Ways");
splitChoiceBox.setValue("1 Way");
splitChoiceBox.setPrefWidth(150);
// instantiate a button and its properties
calcTipButton = new Button("Calculate Tip");
calcTipButton.setMaxWidth(Double.MAX_VALUE);
calcTipButton.setOnAction(e -> CalcButtonClick()) ;
// instantiate a grid pane and its properties
grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10));
grid.add(titleLabel, 0, 0, 2, 1);
grid.addRow(1, checkAmtLabel, checkAmtText);
grid.addRow(2, tipPercentLabel, tipPercentSlider);
grid.addRow(3, splitLabel, splitChoiceBox);
grid.add(calcTipButton, 0, 4, 2, 1);
grid.addRow(5, tipAmtLabel, tipAmtText);
grid.addRow(6, totalLabel, totalText);
grid.addRow(7, amtPerPersonLabel, amtPerPersonText);
// instantiate the grid pane and put items in in grid
Scene scene = new Scene(grid);
scene.getRoot().setStyle("-fx-font: 20 'Comic Sans MS'");
primaryStage.setTitle("Tip Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private void CalcButtonClick() {
/*
Get the check amount from checkAmtText
Get the tip percent from the slider
Get the split the choice box
Tip amount = check amount * tip percent
Total amount = check amount + tip amount
Amount per person = total amount / split
Print the tip amount in tipAmtText
Print the total amount in total Text
Print the split amtPerPerson Text
*/
double tipAmnt, checkAmnt, tipPercent,
totalAmnt, AmntPerPerson;
tipAmnt = Double.parseDouble(tipAmtText.getText());
AmntPerPerson =
Double.parseDouble(amtPerPersonText.getText());
checkAmnt = Double.parseDouble(checkAmtText.getText());
totalAmnt = Double.parseDouble(totalText.getText());
tipPercent = Double.parseDouble(tipPercentLabel.getText());
tipAmnt = checkAmnt * tipPercent;
totalAmnt = checkAmnt + tipAmnt;
tipAmtText.setText(currency.format(tipAmnt));
totalText.setText(currency.format(totalAmnt));
}
private void ResetFields() {
/*
Clear the check amount
Clear the tip amount
Clear the total amount
Clear the amount per person
Set the tip percent slider to 15%
Set the split choice box to “1 Way”
*/
}
}
You should use eventListener or FXML. Second, I think, would be easier. Need example?
UPDATE: (I added an example)
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation((getClass().getResource("Sample.fxml")));
Parent panel = fxmlLoader.load();
Scene scene = new Scene(panel, 300, 150);
primaryStage.setTitle("Sum of two numbers");
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Sample.fxml
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="150.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController">
<children>
<AnchorPane prefHeight="55.0" prefWidth="300.0">
<children>
<HBox prefHeight="25.0" prefWidth="200.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0">
<children>
<Label text="x">
<HBox.margin>
<Insets left="31.0" />
</HBox.margin>
</Label>
<Label text="y">
<HBox.margin>
<Insets left="62.0" />
</HBox.margin>
</Label>
<Label text="z">
<HBox.margin>
<Insets left="62.0" />
</HBox.margin>
</Label>
</children>
</HBox>
<HBox prefHeight="100.0" prefWidth="200.0" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0">
<children>
<TextField fx:id="xTextField" />
<TextField fx:id="yTextField" />
<TextField fx:id="zTextField" />
</children>
</HBox>
</children>
</AnchorPane>
<AnchorPane prefHeight="200.0" prefWidth="200.0">
<HBox AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0">
<children>
<Button mnemonicParsing="false" onAction="#sumIt" text="Sum it!" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0" />
</children>
<children>
<Button mnemonicParsing="false" onAction="#clearAll" text="Clear all!" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0" />
</children>
</HBox>
</AnchorPane>
</children>
</VBox>
SampleController.java
package application;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class SampleController {
#FXML
TextField xTextField, yTextField, zTextField;
public void sumIt() {
int sum;
sum = Integer.parseInt(xTextField.getText()) + Integer.parseInt(yTextField.getText());
zTextField.setText(Integer.toString(sum));
}
public void clearAll() {
xTextField.setText("");
yTextField.setText("");
zTextField.setText("");
}
}

Adding eventhandler to treeitems in javafx [duplicate]

The fxml file is as follows (headers omitted):
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:id="pane"
fx:controller="com.github.parboiled1.grappa.debugger.mainwindow.MainWindowUi">
<top>
<MenuBar BorderPane.alignment="CENTER">
<Menu mnemonicParsing="false" text="File">
<MenuItem fx:id="loadInput" mnemonicParsing="false"
text="Load file" onAction="#loadFileEvent"/>
<MenuItem fx:id="parse" mnemonicParsing="false"
text="Parse" onAction="#parseEvent"/>
<MenuItem fx:id="closeButton" mnemonicParsing="false"
text="Close" onAction="#closeWindowEvent"/>
</Menu>
</MenuBar>
</top>
<center>
<SplitPane dividerPositions="0.5" prefHeight="160.0" prefWidth="200.0"
BorderPane.alignment="CENTER">
<SplitPane dividerPositions="0.5" orientation="VERTICAL">
<TreeView fx:id="traceTree" prefHeight="200.0"
prefWidth="200.0" editable="false"/>
<TextArea fx:id="traceDetail" prefHeight="200.0"
prefWidth="200.0"/>
</SplitPane>
<TextArea fx:id="inputText" prefHeight="200.0" prefWidth="200.0"/>
</SplitPane>
</center>
</BorderPane>
I can set the root of the TreeView with no problem at all. The tree is updated with no problem.
The problem I have is that I cannot manage to have an event fired on a given item in the view. I tried and added a onMouseClicked event with a simple System.out.println() and I can see the event being fired, whichever item I click in the tree. But I cannot manage to get the item which has been clicked in the view at all.
How do I do that?
Register a mouse listener with each tree cell, using a cell factory. I don't know the data type you have in your TreeView, but if it were String it might look something like this:
// Controller class:
public class MainWindowUi {
#FXML
private TreeView<String> traceTree ;
// ...
public void initialize() {
traceTree.setCellFactory(tree -> {
TreeCell<String> cell = new TreeCell<String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty) ;
if (empty) {
setText(null);
} else {
setText(item);
}
}
};
cell.setOnMouseClicked(event -> {
if (! cell.isEmpty()) {
TreeItem<String> treeItem = cell.getTreeItem();
// do whatever you need with the treeItem...
}
});
return cell ;
});
}
// ...
}

Get TreeViewItem item when double clicking on item in a TreeView [duplicate]

The fxml file is as follows (headers omitted):
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0"
xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:id="pane"
fx:controller="com.github.parboiled1.grappa.debugger.mainwindow.MainWindowUi">
<top>
<MenuBar BorderPane.alignment="CENTER">
<Menu mnemonicParsing="false" text="File">
<MenuItem fx:id="loadInput" mnemonicParsing="false"
text="Load file" onAction="#loadFileEvent"/>
<MenuItem fx:id="parse" mnemonicParsing="false"
text="Parse" onAction="#parseEvent"/>
<MenuItem fx:id="closeButton" mnemonicParsing="false"
text="Close" onAction="#closeWindowEvent"/>
</Menu>
</MenuBar>
</top>
<center>
<SplitPane dividerPositions="0.5" prefHeight="160.0" prefWidth="200.0"
BorderPane.alignment="CENTER">
<SplitPane dividerPositions="0.5" orientation="VERTICAL">
<TreeView fx:id="traceTree" prefHeight="200.0"
prefWidth="200.0" editable="false"/>
<TextArea fx:id="traceDetail" prefHeight="200.0"
prefWidth="200.0"/>
</SplitPane>
<TextArea fx:id="inputText" prefHeight="200.0" prefWidth="200.0"/>
</SplitPane>
</center>
</BorderPane>
I can set the root of the TreeView with no problem at all. The tree is updated with no problem.
The problem I have is that I cannot manage to have an event fired on a given item in the view. I tried and added a onMouseClicked event with a simple System.out.println() and I can see the event being fired, whichever item I click in the tree. But I cannot manage to get the item which has been clicked in the view at all.
How do I do that?
Register a mouse listener with each tree cell, using a cell factory. I don't know the data type you have in your TreeView, but if it were String it might look something like this:
// Controller class:
public class MainWindowUi {
#FXML
private TreeView<String> traceTree ;
// ...
public void initialize() {
traceTree.setCellFactory(tree -> {
TreeCell<String> cell = new TreeCell<String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty) ;
if (empty) {
setText(null);
} else {
setText(item);
}
}
};
cell.setOnMouseClicked(event -> {
if (! cell.isEmpty()) {
TreeItem<String> treeItem = cell.getTreeItem();
// do whatever you need with the treeItem...
}
});
return cell ;
});
}
// ...
}

Resources