I cannot set the text for the tempDisplay label by using settext() in connectArduino method. It only can show part of the string, like the symbol "°C", just like the screen shot shows. But the string "input" can be print out actually.
Here is my controller class
import javafx.application.Platform;
import javafx.scene.chart.LineChart;
import javafx.scene.control.*;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ToggleButton;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import jssc.SerialPort;
import static jssc.SerialPort.MASK_RXCHAR;
import jssc.SerialPortEvent;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class MainController {
SerialPort arduinoPort = null;
ObservableList<String> portList;
public String input;
public static double max;
public static double min;
public static String phoneNumber;
public static final String ACCOUNT_SID =
"AC935209d3c44660b4a550e3380249857a";
public static final String AUTH_TOKEN = "42bcd28e23344404c737eb3499d2a747";
final int NUM_OF_POINT = 300;
XYChart.Series series;
#FXML
private ComboBox comboBox;
#FXML
private ToggleButton modeButton;
#FXML
private ToggleButton ledButton;
#FXML
private Button connectButton;
#FXML
private TextArea displayArea;
#FXML
private Label tempDisplay;
#FXML
private NumberAxis xAxis;
#FXML
private NumberAxis yAxis;
#FXML
private LineChart lineChart;
#FXML
private void initialize(){
displayArea.setEditable(false);
detectPort();
comboBox.setPromptText("Port List");
comboBox.setItems(portList);
setLineChart();
//sendSMS();
}
private void detectPort(){
portList = FXCollections.observableArrayList();
String[] serialPortNames = SerialPortList.getPortNames();
portList.addAll(serialPortNames);
}
private void connect(){
disconnectArduino();
if(connectButton.getText().equals("Connect")) {
connectArduino(comboBox.getValue().toString());
}
ledButton.setSelected(false);
}
public boolean connectArduino(String port){
displayArea.appendText("connect Arduino");
if(port.isEmpty()){
alert("Connect Failed!");
return false;
}
else {
connectButton.setText("Disconnect");
boolean success = false;
SerialPort serialPort = new SerialPort(port);
try {
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setEventsMask(MASK_RXCHAR);
serialPort.addEventListener((SerialPortEvent serialPortEvent) -> {
if (serialPortEvent.isRXCHAR()) {
try {
input = serialPort.readString(serialPortEvent
.getEventValue());
System.out.println(input);
if (input.contains("false")) {
alert("Unplugged Sensor");
} else {
Platform.runLater(() -> {
String st = input + " °C";
tempDisplay.setText(st);
// shiftSeriesData(Float.parseFloat(input));
});
}
} catch (SerialPortException ex) {
Logger.getLogger(MainController.class.getName())
.log(Level.SEVERE, null, ex);
alert("No Data Available");
}
}
});
arduinoPort = serialPort;
success = true;
} catch (SerialPortException ex) {
Logger.getLogger(MainController.class.getName())
.log(Level.SEVERE, null, ex);
System.out.println("SerialPortException: " + ex.toString());
alert("No Data Available");
}
return success;
}
}
Here is my fxml class
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToggleButton?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="627.0" prefWidth="664.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<children>
<LineChart fx:id="lineChart" createSymbols="false" layoutY="74.0" prefHeight="343.0" prefWidth="396.0" title="Temperature of Session">
<xAxis>
<NumberAxis autoRanging="false" label="Time (s)" side="BOTTOM" tickUnit="100" fx:id="xAxis" upperBound="300"/>
</xAxis>
<yAxis>
<NumberAxis fx:id="yAxis" autoRanging="false" label="Temperature (°C)" lowerBound="10" side="RIGHT" upperBound="50" />
</yAxis>
</LineChart>
<TextArea fx:id="displayArea" editable="false" layoutX="15.0" layoutY="426.0" prefHeight="186.0" prefWidth="635.0" />
<Label layoutX="94.0" layoutY="14.0" prefHeight="60.0" prefWidth="482.0" text="Team Placeholder Themometer Interface">
<font>
<Font size="24.0" />
</font>
</Label>
<Button fx:id="connectButton" layoutX="475.0" layoutY="145.0" mnemonicParsing="false" onAction="#connectPressed" prefHeight="80.0" prefWidth="131.0" text="Connect">
<font>
<Font size="18.0" />
</font>
</Button>
<Button fx:id="setButton" layoutX="475.0" layoutY="241.0" mnemonicParsing="false" onAction="#setPressed" prefHeight="34.0" prefWidth="131.0" text="Set SMS" />
<Label layoutX="400.0" layoutY="314.0" prefHeight="27.0" prefWidth="131.0" text="Current Temperature" />
<ComboBox fx:id="comboBox" layoutX="475.0" layoutY="94.0" prefHeight="34.0" prefWidth="131.0" />
<ToggleButton fx:id="ledButton" layoutX="540.0" layoutY="360.0" mnemonicParsing="false" onAction="#ledPressed" prefHeight="34.0" prefWidth="109.0" text="Show on LEDs" />
<ToggleButton fx:id="modeButton" layoutX="540.0" layoutY="314.0" mnemonicParsing="false" onAction="#modePressed" prefHeight="34.0" prefWidth="109.0" text="In Fahrenheit" />
<Label fx:id="tempDisplay" layoutX="400.0" layoutY="341.0" prefHeight="39.0" prefWidth="131.0" textFill="#e10707">
<font>
<Font size="32.0" />
</font>
</Label>
</children>
Screen shot for the interface
Related
This question already has an answer here:
How do I add a value to items in a ComboBox in JavaFX
(1 answer)
Closed 4 years ago.
Hi I am trying to populate data from a database into a Combo Box, but when I click on the dropdown menu, it does not list the names of the items correctly. I can't figure out why.
Here is what appears when I click on the combobox image
Any help is appreciated thanks!
Edit:I tried using a String Converter but it still does not display the output . Did I use the String Converter correctly?
OrderController class
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.event.ActionEvent;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
public class Ordercontroller implements Initializable {
#FXML ComboBox<Orderitems> itemdropdown;
#FXML ComboBox<String> droppax;
#FXML ComboBox<String> tablenum;
#FXML
ObservableList<Orderitems> choice = FXCollections.observableArrayList();
ObservableList<String> pax =
FXCollections.observableArrayList("1","2","3","4","5","6","7");
ObservableList<String> tableno =
FXCollections.observableArrayList("1","2","3","4","5","6","7");
#Override
public void initialize(URL location, ResourceBundle resources) {
itemdrop();
}
public void itemdrop(){
itemdropdown.setValue(null);
itemdropdown.setItems(choice);
droppax.setItems(pax);
tablenum.setItems(tableno);
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String path = "C:\\Users\\franc\\Desktop\\Database\\CSIA1.accdb";
String url = "jdbc:ucanaccess://" + path;
Connection conn = DriverManager.getConnection(url);
Statement st = conn.createStatement();
String sql = "Select * from Menu";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
choice.add(new Orderitems(rs.getString("Item")));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Orderitems class
package sample;
import java.awt.*;
import javafx.util.StringConverter;
public class Orderitems extends Ordercontroller{
String Item;
Ordercontroller order = new Ordercontroller();
public Orderitems(String item) {
this.Item = item;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public void start() throws Exception{
itemdropdown.setConverter(new StringConverter<Orderitems>() {
#Override
public String toString(Orderitems object) {
return null;
}
#Override
public Orderitems fromString(String string) {
return null;
}
});}}
Order FXML file
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/8.0.172-ea"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Ordercontroller">
<children>
<TableView fx:id="Ordertable" layoutX="204.0" layoutY="51.0"
prefHeight="200.0" prefWidth="345.0">
<columns>
<TableColumn fx:id="Oitem" prefWidth="75.0" text="Item" />
<TableColumn fx:id="Oprice" prefWidth="75.0" text="Price" />
<TableColumn fx:id="Ospecial" prefWidth="155.0" text="Special
Requests" />
</columns>
</TableView>
<Button layoutX="475.0" layoutY="266.0" mnemonicParsing="false" text="Add
Item" />
<Label layoutX="38.0" layoutY="238.0" text="Table Number" />
<TextArea fx:id="specialreq" layoutX="278.0" layoutY="352.0"
prefHeight="65.0" prefWidth="200.0" text="Special Requests" />
<Button layoutX="82.0" layoutY="312.0" mnemonicParsing="false" text="Load" />
<Label layoutX="68.0" layoutY="68.0" text="No. of Pax" />
<Button layoutX="496.0" layoutY="369.0" mnemonicParsing="false" text="Add"
/>
<Button layoutX="473.0" layoutY="308.0" mnemonicParsing="false"
text="Delete Item" />
<ComboBox fx:id="itemdropdown" layoutX="308.0" layoutY="270.0"
onAction="#itemdrop" prefWidth="150.0" />
<ComboBox fx:id="tablenum" layoutX="34.0" layoutY="270.0"
prefWidth="150.0" />
<ComboBox fx:id="droppax" layoutX="34.0" layoutY="96.0" prefWidth="150.0"
/>
<Button layoutX="28.0" layoutY="14.0" mnemonicParsing="false"
onAction="#returnhome" text="Exit" />
</children>
</AnchorPane>
Try implementing toString on your OrderItem class.
#Override
public String toString() {
return item;
}
I have this fxml layout. When I click on take photo it opens a screen for me to take a picture using web cam
Dialog layout to take pic from web cam
I want the picture captured on the web cam to replace the dummy image on the fxml layout beside take photo button.Here are my files:
FXML layout containing dummy image and take photo button
<HBox prefHeight="79.0" prefWidth="232.0" spacing="30.0">
<children>
<VBox prefHeight="100.0" prefWidth="100.0">
<children>
<ImageView fx:id="profilePic" fitHeight="99.0" fitWidth="118.0" nodeOrientation="INHERIT" pickOnBounds="true">
<image>
<Image url="#../images/profile_photo.png" />
</image>
</ImageView>
</children>
</VBox>
<VBox prefHeight="200.0" prefWidth="100.0">
<children>
<Button mnemonicParsing="false" onAction="#takePhoto" text="Take Photo">
<font>
<Font size="13.0" />
</font>
<VBox.margin>
<Insets bottom="20.0" top="10.0" />
</VBox.margin>
</Button>
<Button mnemonicParsing="false" onAction="#pickPhoto" prefHeight="31.0" prefWidth="85.0" text="Upload
">
<font>
<Font size="13.0" />
</font>
<VBox.margin>
<Insets bottom="10.0" />
</VBox.margin></Button>
</children>
</VBox>
</children>
</HBox>
Controller for the FXML Layout
public class AddParentController implements Initializable {
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void doAll(){
ImageSelection.getImageSelectionInstance().imageProperty()
.addListener((obs, oldImage, newImage) -> profilePic.setImage(newImage));
}
public void takePhoto(){
try {
Stage dialogStage = new Stage(StageStyle.UNDECORATED);
BorderPane root = FXMLLoader.load(getClass().getResource("../views/WebCamPreview.fxml"));
Scene scene = new Scene(root, 850, 390);
dialogStage.setUserData("fromAddParent");
dialogStage.initModality(Modality.APPLICATION_MODAL);
dialogStage.setScene(scene);
dialogStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Dialog Layout containing WebCam Preview
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<BorderPane prefHeight="390.0" prefWidth="850.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controllers.WebCamPreviewController">
<!-- TODO Add Nodes -->
<bottom>
<FlowPane fx:id="fpBottomPane" alignment="CENTER" columnHalignment="CENTER" hgap="50.0" prefHeight="80.0" prefWidth="200.0" style="-fx-background-color:#ccc;">
<children>
<Button fx:id="btnStartCamera" focusTraversable="false" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#stopCamera" prefHeight="40.0" prefWidth="120.0" text="Capture">
<font>
<Font name="Segoe UI" size="18.0" fx:id="x1" />
</font>
</Button>
<Button fx:id="btnProceedCamera" focusTraversable="false" font="$x1" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#proceed" prefHeight="40.0" prefWidth="120.0" text="Proceed" />
<Button fx:id="btnResetCamera" focusTraversable="false" font="$x1" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#startCamera" prefHeight="40.0" prefWidth="120.0" text="Reset" />
<Button fx:id="btnDisposeCamera" focusTraversable="false" minHeight="-Infinity" minWidth="-Infinity" mnemonicParsing="false" onAction="#disposeCamera" prefHeight="40.0" prefWidth="120.0" text="Close">
<font>
<Font name="Segoe UI" size="18.0" fx:id="x11" />
</font>
</Button>
</children>
</FlowPane>
</bottom>
<center>
<BorderPane fx:id="bpWebCamPaneHolder" prefHeight="200.0" prefWidth="200.0">
<center>
<ImageView fx:id="imgWebCamCapturedImage" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" BorderPane.alignment="CENTER" />
</center></BorderPane>
</center>
<top>
<GridPane minHeight="-Infinity" minWidth="-Infinity" prefHeight="80.0" style="-fx-background-color:#ccc;
">
<children>
<Label text="Webcam Image Capture" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.halignment="CENTER" GridPane.hgrow="ALWAYS" GridPane.rowIndex="0" GridPane.rowSpan="1" GridPane.valignment="CENTER" GridPane.vgrow="ALWAYS">
<font>
<Font name="Segoe UI" size="34.0" />
</font>
<GridPane.margin>
<Insets top="10.0" />
</GridPane.margin>
</Label>
</children>
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" maxWidth="795.0" minWidth="10.0" prefWidth="418.0" />
<ColumnConstraints hgrow="SOMETIMES" maxWidth="502.0" minWidth="10.0" prefWidth="482.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>
</top>
</BorderPane>
WebCam Preview Controller
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;
import com.github.sarxos.webcam.WebcamPanel;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import com.github.sarxos.webcam.Webcam;
import javafx.stage.Stage;
public class WebCamPreviewController implements Initializable {
#FXML Button btnStartCamera;
#FXML Button btnProceedCamera;
#FXML Button btnDisposeCamera,btnResetCamera;
#FXML BorderPane bpWebCamPaneHolder;
#FXML FlowPane fpBottomPane;
#FXML ImageView imgWebCamCapturedImage;
private BufferedImage grabbedImage;
private WebcamPanel selWebCamPanel = null;
private Webcam selWebCam = null;
private boolean stopCamera = false;
private ObjectProperty<Image> imageProperty = new SimpleObjectProperty<Image>();
Image mainiamge;
private String userData;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
fpBottomPane.setDisable(true);
try{
initializeWebCam(0);
}catch(Exception e){
e.printStackTrace();
}
Platform.runLater(() -> {
userData = (String) fpBottomPane.getScene().getWindow().getUserData();
setImageViewSize();
});
}
protected void setImageViewSize() {
double height = bpWebCamPaneHolder.getHeight();
double width = bpWebCamPaneHolder.getWidth();
imgWebCamCapturedImage.setFitHeight(height);
imgWebCamCapturedImage.setFitWidth(width);
imgWebCamCapturedImage.prefHeight(height);
imgWebCamCapturedImage.prefWidth(width);
imgWebCamCapturedImage.setPreserveRatio(true);
}
protected void initializeWebCam(final int webCamIndex) {
Task<Void> webCamIntilizer = new Task<Void>() {
#Override
protected Void call() throws Exception {
if(selWebCam == null)
{
selWebCam = Webcam.getWebcams().get(webCamIndex);
selWebCam.open();
}else
{
closeCamera();
selWebCam = Webcam.getWebcams().get(webCamIndex);
selWebCam.open();
}
startWebCamStream();
return null;
}
};
new Thread(webCamIntilizer).start();
fpBottomPane.setDisable(false);
btnProceedCamera.setDisable(true);
btnResetCamera.setDisable(true);
}
protected void startWebCamStream() {
stopCamera = false;
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
while (!stopCamera) {
try {
if ((grabbedImage = selWebCam.getImage()) != null) {
Platform.runLater(new Runnable() {
#Override
public void run() {
mainiamge = SwingFXUtils
.toFXImage(grabbedImage, null);
imageProperty.set(mainiamge);
}
});
grabbedImage.flush();
}
} catch (Exception e) {
} finally {
}
}
return null;
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
imgWebCamCapturedImage.imageProperty().bind(imageProperty);
}
private void closeStage() {
((Stage) fpBottomPane.getScene().getWindow()).close();
}
private void closeCamera()
{
if(selWebCam != null)
{
selWebCam.close();
}
}
public void proceed(){
ImageSelection.getImageSelectionInstance().setImage(imgWebCamCapturedImage.getImage());
AddParentController apc = new AddParentController();
apc.doAll();
closeStage();
}
public void proceedToAddPartner(){
}
public void stopCamera(ActionEvent event)
{
stopCamera = true;
btnStartCamera.setDisable(true);
btnResetCamera.setDisable(false);
btnProceedCamera.setDisable(false);
}
public void startCamera(ActionEvent event)
{
stopCamera = false;
startWebCamStream();
btnStartCamera.setDisable(false);
btnResetCamera.setDisable(true);
btnProceedCamera.setDisable(true);
}
public void disposeCamera(ActionEvent event)
{
//stopCamera = true;
//closeCamera();
//Webcam.shutdown();
//btnStopCamera.setDisable(true);
//btnStartCamera.setDisable(true);
closeStage();
}
}
Image Model
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.image.Image;
public class ImageSelection {
private final ObjectProperty<Image> image = new SimpleObjectProperty<>();
private static ImageSelection imageSelectionInstance= new ImageSelection();
private ImageSelection(){}
public static ImageSelection getImageSelectionInstance() {
return imageSelectionInstance;
}
public ObjectProperty<Image> imageProperty() {
return image ;
}
public final void setImage(Image image) {
imageProperty().set(image);
}
public final Image getImage()
{
return imageProperty().get();
}
}
The challenge is to make the Image captured by the web cam to display in profilPic ImageView on the AddParent FXML Layout.
I have a JavaFx project with two stages. The main stage has the ability to launch second stage .In second stage I have a textfield I want to put some data into textfield and send it to the main stage and set it as a label .Here is my code:
MAIN:
package sample;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("/sample/sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
MAIN CONTROLLER:
package sample;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
#FXML
private javafx.scene.control.Button kbutton;
#FXML
private javafx.scene.control.Button obutton;
#FXML
public Label label;
public TextField popField;
#FXML
public String text;
#FXML
private void konfButton() throws Exception{
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/sample/konfview.fxml"));
Parent root = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.showAndWait();
} catch(Exception e) {
e.printStackTrace();
}
}
public void myFunction( String text){
popField.setText(text);
}
#FXML
private void oblButton() throws Exception{
try {
// get a handle to the stage
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/sample/sample.fxml"));
Parent root = (Parent) fxmlLoader.load();
Controller Controller=fxmlLoader.getController();
Stage stage = (Stage) obutton.getScene().getWindow();
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
MAIN FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
</rowConstraints>
<children>
<Pane prefHeight="400.0" prefWidth="600.0">
<children>
<Label layoutX="69.0" layoutY="81.0" text="previous reading" />
<Label layoutX="69.0" layoutY="115.0" text="current reading" />
<Label layoutX="71.0" layoutY="154.0" text="months" />
<Label layoutX="108.0" layoutY="14.0" text="Price">
<font>
<Font name="Comic Sans MS" size="18.0" />
</font>
</Label>
<Label layoutX="97.0" layoutY="51.0" text="Give details">
<font>
<Font name="Comic Sans MS" size="12.0" />
</font>
</Label>
<Button fx:id="kbutton" layoutX="74.0" layoutY="197.0" mnemonicParsing="false" onAction="#konfButton" text="Configure" />
<Button fx:id="obutton" layoutX="197.0" layoutY="197.0" mnemonicParsing="false" onAction="#oblButton" text="OK" />
<TextField fx:id="popField" layoutX="172.0" layoutY="77.0" />
<TextField fx:id="bieField" layoutX="172.0" layoutY="111.0" />
<TextField fx:id="mcField" layoutX="172.0" layoutY="150.0" />
<Label fx:id="label" layoutX="119.0" layoutY="245.0" prefHeight="37.0" prefWidth="333.0" text="text" />
</children>
</Pane>
</children>
</GridPane>
SECOND CONTROLLER:
package sample;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.io.IOException;
public class ControllerConf {
#FXML
public TextField palField;
public Label label;
public String text;
#FXML
private TextField dysField1;
#FXML
private javafx.scene.control.Button cancelB;
#FXML
public javafx.scene.control.Button saveB;
#FXML
private void cancelButton(){
// get a handle to the stage
Stage stage = (Stage) cancelB.getScene().getWindow();
// do what you have to do
stage.close();
}
#FXML
public Stage saveButton(){
try {
FXMLLoader loader=new
FXMLLoader(getClass().getResource("/sample/sample.fxml"));
Parent root = (Parent) loader.load();
Controller Controller=loader.getController();
Controller.myFunction(palField.getText());
Stage primaryStage = (Stage) saveB.getScene().getWindow();
primaryStage.close();
return primaryStage;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
SECOND FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.ControllerConf">
<children>
<Label layoutX="185.0" layoutY="28.0" prefHeight="17.0" prefWidth="314.0" text="Give details">
<font>
<Font name="Comic Sans MS" size="20.0" />
</font>
</Label>
<Label layoutX="48.0" layoutY="95.0" text="Price pre KWh" />
<Label layoutX="48.0" layoutY="135.0" text="Price pre item" />
<TextField fx:id="palField" layoutX="252.0" layoutY="91.0" onAction="#saveButton" />
<TextField fx:id="dysField" layoutX="252.0" layoutY="131.0" />
<Button fx:id="cancelB" layoutX="159.0" layoutY="208.0" mnemonicParsing="false" onAction="#cancelButton" text="Cancel">
<font>
<Font name="Comic Sans MS" size="12.0" />
</font>
</Button>
<Button fx:id="saveB" layoutX="292.0" layoutY="209.0" mnemonicParsing="false" onAction="#saveButton" text="Save">
<font>
<Font name="Comic Sans MS" size="12.0" />
</font>
</Button>
</children>
</AnchorPane>
I created MyFunction wchich set text and it's working fine when created new stage but doesnt for main stage.Do you know how to solve it?Thanks in advance.enter code here
I'm having issues showing new additions to a class in a TableView for my JavaFX/FXML program. I've looked at countless tutorials but the missing piece still escapes me.
I had some errors that got fixed here: JavaFX Adding Rows to TableView on Different Page
And then found a new tutorial to sort of follow that explained things a bit better than the first one I was following (their app is a bit different than what I have to do) here: http://code.makery.ch/library/javafx-8-tutorial/part2/
I have an output printing the name field out to the console just to make sure it is pulling the right values from the add form. I also changed the way I navigated between Add Part and the Main window (nothing else works right now). I feel so silly asking this, but Java is the one language I haven't been able to wrap my head around.
Any ideas on why it isn't updating are greatly appreciated.
IMS.java
package ims;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class IMS extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Part> partData = FXCollections.observableArrayList();
public IMS() {
partData.add(new Part("Part A", 3, 4.00, 1, 5));
partData.add(new Part("Part B", 2, 14.00, 1, 15));
}
public ObservableList<Part> getPartData(){
return partData;
}
#Override
public void start(Stage stage) throws Exception {
// Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = (Parent) loader.load();
FXMLDocumentController ctrl = loader.getController();
ctrl.setMainApp(this);
Scene scene = new Scene(root);
scene.getStylesheets().add("style.css");
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLDocumentController.java
package ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private TableView<Part> partTable;
#FXML
private TableColumn<Part, Integer> partIDColumn;
#FXML
private TableColumn<Part, String> nameColumn;
#FXML
private TableColumn<Part, Integer> inventoryColumn;
#FXML
private TableColumn<Part, Double> priceColumn;
private IMS mainApp;
public FXMLDocumentController(){
}
#FXML
private void addPart(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("addPart.fxml"));
Parent add_part_parent = (Parent) loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(add_part_parent));
stage.show();
}
#FXML
private void modifyPart(ActionEvent event) throws IOException {
Parent modify_part_parent = FXMLLoader.load(getClass().getResource("modifyPart.fxml"));
Scene modify_part_scene = new Scene(modify_part_parent);
modify_part_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(modify_part_scene);
app_stage.show();
}
#FXML
private void addProduct(ActionEvent event) throws IOException {
Parent add_product_parent = FXMLLoader.load(getClass().getResource("addProduct.fxml"));
Scene add_product_scene = new Scene(add_product_parent);
add_product_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(add_product_scene);
app_stage.show();
}
#FXML
private void modifyProduct(ActionEvent event) throws IOException {
Parent modify_product_parent = FXMLLoader.load(getClass().getResource("modifyProduct.fxml"));
Scene modify_product_scene = new Scene(modify_product_parent);
modify_product_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(modify_product_scene);
app_stage.show();
}
#FXML
private void closeProgram(ActionEvent event) throws IOException {
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.close();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
// inventoryColumn.setCellValueFactory(cellData -> cellData.getValue().instockProperty().asObject());
// priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty().asObject());
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
inventoryColumn.setCellValueFactory(new PropertyValueFactory<>("instock"));
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
}
public void setMainApp(IMS mainApp) {
this.mainApp = mainApp;
// Add observable list data to the table
partTable.setItems(mainApp.getPartData());
}
#FXML
private void handleDeletePart(){
int selectedIndex = partTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0){
partTable.getItems().remove(selectedIndex);
} else {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("No Part Selected");
alert.setHeaderText("No Part Selected");
alert.setContentText("Please select the part you would like to delete.");
alert.showAndWait();
}
}
}
FXMLDocument.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.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.collections.*?>
<?import fxmltableview.*?>
<?import ims.Part?>
<?import ims.Inhouse?>
<?import ims.Outsourced?>
<BorderPane id="main" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.FXMLDocumentController" >
<top>
<Label fx:id="mainTitle" text="Inventory Management System" />
</top>
<center>
<HBox fx:id="holding">
<children>
<VBox styleClass="contentBox">
<children>
<HBox styleClass="topBox">
<HBox styleClass="subHeading">
<Label text="Parts" />
</HBox>
<HBox styleClass="searchBox">
<Button text="Search" />
<TextField />
</HBox>
</HBox>
<TableView fx:id="partTable" styleClass="dataTable">
<columns>
<TableColumn fx:id="partIDColumn" text="Part ID" />
<TableColumn fx:id="nameColumn" text="Part Name" />
<TableColumn fx:id="inventoryColumn" text="Inventory Level" />
<TableColumn fx:id="priceColumn" text="Price/Cost per Unit" />
</columns>
</TableView>
<HBox styleClass="modificationButtons">
<children>
<Button onAction="#addPart" text="Add" />
<Button onAction="#modifyPart" text="Modify" />
<Button text="Delete" />
</children>
</HBox>
</children>
</VBox>
<VBox styleClass="contentBox">
<children>
<HBox styleClass="topBox">
<HBox styleClass="subHeading">
<Label text="Products" />
</HBox>
<HBox styleClass="searchBox">
<Button text="Search" />
<TextField />
</HBox>
</HBox>
<TableView fx:id="productTable" styleClass="dataTable">
<columns>
<TableColumn text="Part ID" />
<TableColumn text="Part Name" />
<TableColumn text="Inventory Level" />
<TableColumn text="Price/Cost per Unit" />
</columns>
</TableView>
<HBox styleClass="modificationButtons">
<children>
<Button onAction="#addProduct" text="Add" />
<Button onAction="#modifyProduct" text="Modify" />
<Button text="Delete" />
</children>
</HBox>
</children>
</VBox>
</children>
</HBox>
</center>
<bottom>
<HBox fx:id="exitButton">
<children>
<Button onAction="#closeProgram" text="Exit" />
</children>
</HBox>
</bottom>
</BorderPane>
Part.java
package ims;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* #author chelseacamper
*/
public class Part {
private final SimpleStringProperty name;
private final SimpleIntegerProperty instock;
private final SimpleDoubleProperty price;
private final SimpleIntegerProperty min;
private final SimpleIntegerProperty max;
public Part(){
this("", 0, 0.00, 0, 0);
}
public Part(String name, int instock, double price, int min, int max) {
this.name = new SimpleStringProperty(name);
this.instock = new SimpleIntegerProperty(instock);
this.price = new SimpleDoubleProperty(price);
this.min = new SimpleIntegerProperty(min);
this.max = new SimpleIntegerProperty(max);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
public Double getPrice() {
return price.get();
}
public void setPrice(Double price) {
this.price.set(price);
}
public DoubleProperty priceProperty(){
return price;
}
public int getInstock() {
return instock.get();
}
public void setInstock(int instock) {
this.instock.set(instock);
}
public IntegerProperty instockProperty(){
return instock;
}
public int getMin() {
return min.get();
}
public void setMin(int min) {
this.min.set(min);
}
public IntegerProperty minProperty(){
return min;
}
public int getMax() {
return max.get();
}
public void setMax(int max) {
this.max.set(max);
}
public IntegerProperty maxProperty(){
return max;
}
}
addPartController.java
package ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author chelseacamper
*/
public class AddPartController implements Initializable {
#FXML
ToggleButton inhouse;
#FXML
ToggleButton outsourced;
#FXML
Label inhouseLabel;
#FXML
Label outsourcedLabel;
#FXML
TextField inhouseTextField;
#FXML
TextField outsourcedTextField;
#FXML
private TableView<Part> partTable;
#FXML
private TextField partNameField;
#FXML
private TextField partInstockField;
#FXML
private TextField partPriceField;
#FXML
private TextField partMaxField;
#FXML
private TextField partMinField;
#FXML
private Button cancel;
#FXML
private Button save;
private Part part = new Part();
// private ObservableList<Part> partData = FXCollections.observableArrayList();
private ObservableList<Part> tableItems;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
inhouseLabel.visibleProperty().bind( inhouse.selectedProperty() );
outsourcedLabel.visibleProperty().bind( outsourced.selectedProperty() );
inhouseTextField.visibleProperty().bind( inhouse.selectedProperty() );
outsourcedTextField.visibleProperty().bind( outsourced.selectedProperty() );
inhouseLabel.managedProperty().bind( inhouse.selectedProperty() );
outsourcedLabel.managedProperty().bind( outsourced.selectedProperty() );
inhouseTextField.managedProperty().bind( inhouse.selectedProperty() );
outsourcedTextField.managedProperty().bind( outsourced.selectedProperty() );
}
#FXML
public void addInhouse(ActionEvent event) throws IOException{
// Part tempPart = new Part(partNameField.getText(),
// Integer.parseInt(partInstockField.getText()),
// Double.parseDouble(partPriceField.getText()),
// Integer.parseInt(partMaxField.getText()),
// Integer.parseInt(partMinField.getText()));
// tableItems.add(new Part(partNameField.getText(),
// Integer.parseInt(partInstockField.getText()),
// Double.parseDouble(partPriceField.getText()),
// Integer.parseInt(partMaxField.getText()),
// Integer.parseInt(partMinField.getText())
// ));
part
.setName(partNameField.getText());
part.setPrice(Double.parseDouble(partPriceField.getText()));
part.setInstock(Integer.parseInt(partInstockField.getText()));
part.setMin(Integer.parseInt(partMinField.getText()));
part.setMax(Integer.parseInt(partMaxField.getText()));
System.out.println(partNameField.getText());
Stage stage = (Stage) cancel.getScene().getWindow();
stage.close();
}
#FXML
private void close(ActionEvent event) throws IOException {
Stage stage = (Stage) cancel.getScene().getWindow();
stage.close();
}
void setTableItems(ObservableList<Part> tableItems) {
this.tableItems = tableItems;
}
}
addPart.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane id="addPage" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.AddPartController">
<stylesheets>
<String fx:value="style.css" />
</stylesheets>
<fx:define>
<ToggleGroup fx:id="inOutGroup" />
</fx:define>
<center>
<VBox fx:id="verticalHolding">
<children>
<HBox fx:id="topRow">
<Label text="Add Part"/>
<RadioButton fx:id="inhouse" toggleGroup="$inOutGroup" text="In-House"/>
<RadioButton fx:id="outsourced" toggleGroup="$inOutGroup" selected="true" text="Outsourced"/>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="ID" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField promptText="Auto Gen - Disabled" disable="true" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Name" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partNameField" promptText="Part Name" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Inv" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partInstockField" promptText="Inv" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Price/Cost" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partPriceField" promptText="Price/Cost" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Max" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField styleClass="smallTextField" fx:id="partMaxField" promptText="Max" />
<Label text="Min" />
<TextField styleClass="smallTextField" fx:id="partMinField" promptText="Min" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label fx:id="inhouseLabel" text="Machine ID" />
<Label fx:id="outsourcedLabel" text="Company Name" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="inhouseTextField" promptText="Mach ID" />
<TextField fx:id="outsourcedTextField" promptText="Comp Nm" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
</HBox>
<HBox styleClass="halfWidthRight">
<Button onAction="#addInhouse" fx:id="save" text="Save" />
<Button onAction="#close" fx:id="cancel" text="Cancel" />
</HBox>
</HBox>
</children>
</VBox>
</center>
</BorderPane>
I'm trying to integrate a Digital Clock in a label, in a FXML controller, but it doesnt work, it doesnt'update, only show the original text of the label ( dunno )
Fxml:
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="320.0" prefWidth="480.0" style="-fx-background-color: SteelBlue;" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="simulazione.esame.ControllerPannello">
<children>
<Label fx:id="orario" layoutX="32.0" layoutY="65.0" prefHeight="25.0" prefWidth="247.0" text="dunno" />
<ChoiceBox fx:id="settimana" layoutX="14.0" layoutY="116.0" prefWidth="150.0" />
<Label layoutX="195.0" layoutY="108.0" text="Stato Impianto" />
<RadioButton fx:id="onRadio" layoutX="207.0" layoutY="129.0" mnemonicParsing="false" text="on" />
<RadioButton fx:id="offRadio" layoutX="263.0" layoutY="129.0" mnemonicParsing="false" text="off" />
<AnchorPane layoutX="181.0" layoutY="180.0" prefHeight="135.0" prefWidth="289.0">
<children>
<Label layoutX="14.0" layoutY="23.0" text="Temp per raffreddamento" />
<Label layoutX="14.0" layoutY="74.0" text="Temp per riscaldamento" />
<TextField layoutX="176.0" layoutY="19.0" prefHeight="25.0" prefWidth="79.0" />
<TextField layoutX="176.0" layoutY="70.0" prefHeight="25.0" prefWidth="79.0" />
</children>
</AnchorPane>
</children>
</AnchorPane>
Fxml controller:
import java.net.URL;
import java.util.Calendar;
import java.util.ResourceBundle;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.util.Duration;
/**
*
* #author Antonio
*/
public class ControllerPannello implements Initializable {
#FXML
private ChoiceBox settimana;
#FXML
private Label orario, boh;
#FXML
private RadioButton onRadio, offRadio;
private ObservableList<String> sett =
FXCollections.<String>observableArrayList("Lunedì", "Martedì", "Mercoledì",
"Giovedì", "Venerdì", "Sabato", "Domenica");
ToggleGroup stato = new ToggleGroup();
#FXML
private void handleButtonAction(ActionEvent event) {
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
onRadio.setToggleGroup(stato);
offRadio.setToggleGroup(stato);
settimana.setItems(sett);
orario = new DigitalClock();
}
}
DigitalClock.java
import java.io.IOException;
import java.net.URL;
import javafx.animation.*;
import javafx.event.*;
import javafx.scene.control.Label;
import javafx.util.Duration;
import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
class DigitalClock extends Label {
public DigitalClock() {
bindToTime();
}
// the digital clock updates once a second.
public void bindToTime() {
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(0),
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
Calendar time = Calendar.getInstance();
String hourString = StringUtilities.pad(2, ' ', time.get(Calendar.HOUR) == 0 ? "12" : time.get(Calendar.HOUR) + "");
String minuteString = StringUtilities.pad(2, '0', time.get(Calendar.MINUTE) + "");
String secondString = StringUtilities.pad(2, '0', time.get(Calendar.SECOND) + "");
String ampmString = time.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM";
setText(hourString + ":" + minuteString + ":" + secondString + " " + ampmString);
}
}
),
new KeyFrame(Duration.seconds(1))
);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
}
class StringUtilities {
/**
* Creates a string left padded to the specified width with the supplied padding character.
* #param fieldWidth the length of the resultant padded string.
* #param padChar a character to use for padding the string.
* #param s the string to be padded.
* #return the padded string.
*/
public static String pad(int fieldWidth, char padChar, String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length(); i < fieldWidth; i++) {
sb.append(padChar);
}
sb.append(s);
return sb.toString();
}
}