I'm designing a custom JavaFX node using FXML. This node fires a custom event.
And I would like to know how to add an event handler to the custom event in the FXML of the parent of this node.
I created my handler, passed it to the child as an object property and hooked it into the event system via the setEventHandler method. But it throws me an error when the event is fired.
Custom event code :
public class ValueUpdatedEvent extends Event {
public static final EventType<ActionEvent> VALUE =
new EventType<>(Event.ANY, "VALUE_UPDATED");
private float value;
public ValueUpdatedEvent() {
super(VALUE);
}
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
}
Child component controller :
public class CharacteristicBar extends Component {
#FXML
private JFXTextField field;
#FXML
private JFXProgressBar bar;
#FXML
private JFXButton plus;
#FXML
JFXButton minus;
private ObjectProperty<EventHandler<ValueUpdatedEvent>> onValueUpdated = new ObjectPropertyBase<EventHandler<ValueUpdatedEvent>>() {
#Override
public Object getBean() {
return CharacteristicBar.this;
}
#Override protected void invalidated() {
setEventHandler(new EventType<>(Event.ANY, "onValueUpdated"), get());
}
#Override
public String getName() {
return "onValueUpdated";
}
};
private SimpleFloatProperty value = new SimpleFloatProperty();
private boolean readonly = false;
public CharacteristicBar() {
super("CharacteristicBar.fxml");
value.addListener(
newValue -> {
ValueUpdatedEvent event = new ValueUpdatedEvent();
event.setValue(value.get());
fireEvent(event);
}
);
bar.progressProperty().bind(this.value);
if (this.readonly) {
this.field.setEditable(false);
this.minus.setVisible(false);
this.plus.setVisible(false);
}
}
#FXML
private void handleInput(KeyEvent event) {
try {
value.set(Float.parseFloat(field.getText()) / 20f);
} catch (NumberFormatException exception) {
field.setText("");
}
}
public float getValue() {
return value.get() * 20f;
}
#FXML
public void handleClickPlus(ActionEvent event) {
this.value.set((this.value.get() * 20f + 1f) / 20f);
this.field.setText(String.valueOf(this.value.get() * 20));
}
#FXML
public void handleClickMinus(ActionEvent event) {
this.value.set((this.value.get() * 20f - 1f) / 20f);
this.field.setText(String.valueOf(this.value.get() * 20));
}
public boolean isReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
this.readonly = readonly;
this.field.setEditable(!readonly);
this.minus.setVisible(!readonly);
this.plus.setVisible(!readonly);
}
public EventHandler<ValueUpdatedEvent> getOnValueUpdated() {
return onValueUpdated.get();
}
public ObjectProperty<EventHandler<ValueUpdatedEvent>> onValueUpdatedProperty() {
return onValueUpdated;
}
public void setOnValueUpdated(EventHandler<ValueUpdatedEvent> onValueUpdated) {
this.onValueUpdated.set(onValueUpdated);
}
}
Parent's FXML :
<CharacteristicBar fx:id="courageBar" onBarValueChanged="#handleChangeCou"
GridPane.columnIndex="1" GridPane.rowIndex="7"/>
Handler in parent's controller:
#FXML
public void handleChangeCou(ValueUpdatedEvent event){
System.out.println(event.getValue());
}
Still, my event handler isn't called.
Do you guys have any clue on how to hook my handler with the event system ?
Thanks in advance
I could not get the custom event to work but instead I used properties to achieve my goal. Maybe it's intendend this way in JavaFX
I'm trying to push my data that I'm getting from a RethinkDB into a JavaFx TableView, however, the changes do not appear in the tableview and I can't figure out why.
I'm pretty new to JavaFx so I hope you can help me.
Here are my classes : (I didn't include my memory classes where I save the data from the DB)
RethinkDBConnect class
public class RethinkDBConnect {
public static final RethinkDB r = RethinkDB.r;
GsonConverter con = new GsonConverter();
JiraTicketBody body = new JiraTicketBody();
ViewController viewcon = new ViewController();
TicketDataProperty tickprop = new TicketDataProperty(null, null, null, null, null, null);
public void Connection(){
viewcon.list.add(newTicketDataProperty
("test","test","test","test","test","test"));
}
}
TicketDataProperty class
public class TicketDataProperty {
private final SimpleStringProperty key;
private final SimpleStringProperty prioritaet;
private final SimpleStringProperty erstellt;
private final SimpleStringProperty status;
private final SimpleStringProperty zustand;
private final SimpleStringProperty beschreibung;
public TicketDataProperty(String key, String prioritaet, String erstellt,
String status, String zustand, String beschreibung)
{
this.key = new SimpleStringProperty(key);
this.prioritaet = new SimpleStringProperty(prioritaet);
this.erstellt = new SimpleStringProperty(erstellt);
this.status = new SimpleStringProperty(status);
this.zustand = new SimpleStringProperty(zustand);
this.beschreibung = new SimpleStringProperty(beschreibung);
}
public String getKey() {
return key.get();
}
public void setKey(String value) {
key.set(value);
}
public String getPrioritaet() {
return prioritaet.get();
}
public void setPrioritaet(String value) {
prioritaet.set(value);
}
public String getErstellt() {
return erstellt.get();
}
public void setErstellt(String value) {
erstellt.set(value);
}
public String getStatus() {
return status.get();
}
public void setStatus(String value) {
status.set(value);
}
public String getZustand() {
return zustand.get();
}
public void setZustand(String value) {
zustand.set(value);
}
public String getBeschreibung() {
return beschreibung.get();
}
public void setBeschreibung(String value) {
beschreibung.set(value);
}
}
ViewController class
public class ViewController implements Initializable {
TicketDataProperty tickdat = new TicketDataProperty(null, null, null, null, null, null);
#FXML private TableView <TicketDataProperty> table;
#FXML private TableColumn <TicketDataProperty,String> key;
#FXML private TableColumn <TicketDataProperty,String> prioritaet;
#FXML private TableColumn <TicketDataProperty,String> erstellt;
#FXML private TableColumn <TicketDataProperty,String> status;
#FXML private TableColumn <TicketDataProperty,String> zustand;
#FXML private TableColumn <TicketDataProperty,String> beschreibung;
public ObservableList<TicketDataProperty> list = FXCollections.observableArrayList(
new TicketDataProperty("example","example","example","example","example","example")
);
#Override
public void initialize(URL location, ResourceBundle resources) {
key.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("key"));
prioritaet.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("prioritaet"));
erstellt.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("erstellt"));
status.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("status"));
zustand.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("zustand"));
beschreibung.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("beschreibung"));
table.setItems(list);
}
}
GsonConverter class
public class GsonConverter {
public JiraTicketBody gson(String json)
{
Gson gson = new Gson();
JiraTicketBody BodyObj = gson.fromJson(json,JiraTicketBody.class);
return BodyObj;
}
}
Main class
public class Main extends Application
{
//ViewXML
#Override
public void start(Stage primaryStage) throws IOException
{
Parent root = FXMLLoader.load(getClass().getResource("/view/ViewXML.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("Ticket System Application");
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
public static void main(String[] args)
{
try {
//ViewXML
launch(args);
RethinkDBConnect obj = new RethinkDBConnect();
obj.Connection();
} catch(Exception e) {
}
}
}
There are two issues with the code you have posted.
As stated in the documentation, Application.launch() blocks until the application exits. So you don't even create the RethinkDBConnection class until the application is in the process of closing. You should consider the start() method to be the entry point to the application, and should have no code other than launch() in the main(...) method. Anything you do in a JavaFX application should be done in the start(...) or init(...) methods, or in methods invoked from there, etc.
In this case, since you don't seem to need RethinkDBConnection from outside the controller, I see no reason not to create RethinkDBConnect from the controller itself.
You need to update the list that belongs to the controller. Instead, you are creating a new object that happens to be the same class as the controller, and updating the list that belongs to that object. Obviously, that list has nothing at all to do with the table. You need to pass a reference to the actual list that is used as the backing list for the table to the RethinkDBController instance.
So your code should look like:
public class RethinkDBConnection {
// public static final RethinkDB r = RethinkDB.r;
// GsonConverter con = new GsonConverter();
// JiraTicketBody body = new JiraTicketBody();
private final ObservableList<TicketDataProperty> dataList ;
public RethinkDBConnection(ObservableList<TicketDataProperty> dataList) {
this.dataList = dataList ;
}
public void connect(){
dataList.add(new TicketDataProperty
("test","test","test","test","test","test"));
}
}
Then in the controller you can do:
public class ViewController implements Initializable {
#FXML private TableView <TicketDataProperty> table;
#FXML private TableColumn <TicketDataProperty,String> key;
#FXML private TableColumn <TicketDataProperty,String> prioritaet;
#FXML private TableColumn <TicketDataProperty,String> erstellt;
#FXML private TableColumn <TicketDataProperty,String> status;
#FXML private TableColumn <TicketDataProperty,String> zustand;
#FXML private TableColumn <TicketDataProperty,String> beschreibung;
private ObservableList<TicketDataProperty> list = FXCollections.observableArrayList(
new TicketDataProperty("example","example","example","example","example","example")
);
#Override
public void initialize(URL location, ResourceBundle resources) {
key.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("key"));
prioritaet.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("prioritaet"));
erstellt.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("erstellt"));
status.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("status"));
zustand.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("zustand"));
beschreibung.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("beschreibung"));
table.setItems(list);
RethinkDBConnection connection = new RethinkDBConnection(list);
connection.connect();
}
}
And your Main class should just be:
public class Main extends Application
{
//ViewXML
#Override
public void start(Stage primaryStage) throws IOException
{
Parent root = FXMLLoader.load(getClass().getResource("/view/ViewXML.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("Ticket System Application");
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
If you really do need access to your RethinkDBConnection instance outside the controller, then modify the controller as follows:
public class ViewController implements Initializable {
#FXML private TableView <TicketDataProperty> table;
#FXML private TableColumn <TicketDataProperty,String> key;
#FXML private TableColumn <TicketDataProperty,String> prioritaet;
#FXML private TableColumn <TicketDataProperty,String> erstellt;
#FXML private TableColumn <TicketDataProperty,String> status;
#FXML private TableColumn <TicketDataProperty,String> zustand;
#FXML private TableColumn <TicketDataProperty,String> beschreibung;
private ObservableList<TicketDataProperty> list = FXCollections.observableArrayList(
new TicketDataProperty("example","example","example","example","example","example")
);
#Override
public void initialize(URL location, ResourceBundle resources) {
key.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("key"));
prioritaet.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("prioritaet"));
erstellt.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("erstellt"));
status.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("status"));
zustand.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("zustand"));
beschreibung.setCellValueFactory(new PropertyValueFactory<TicketDataProperty,String>("beschreibung"));
table.setItems(list);
}
public ObservableList<TicketDataProperty> getDataList() {
return list ;
}
}
and use this version of Main:
public class Main extends Application
{
//ViewXML
#Override
public void start(Stage primaryStage) throws IOException
{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/ViewXML.fxml"));
Parent root = loader.load();
ViewController controller = loader.getController();
RethinkDBConnection connection = new RethinkDBConnection(controller.getDataList());
connection.connect();
Scene scene = new Scene(root);
primaryStage.setTitle("Ticket System Application");
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Note that I renamed some classes and methods to adhere to standard naming conventions.
Trying to make a dictionary using JavaFx.
Here is my Controller class-
public class MainUIController implements Initializable {
DatabaseManager db=new DatabaseManager();
ObservableList<OvidhanMeaning> MeaningList;
#FXML
private TextField searchField;
#FXML
private ImageView searchIcon;
#FXML
private ImageView aboutIcon;
#FXML
private TableView<OvidhanMeaning> ovidhanTable;
#FXML
private TableColumn<OvidhanMeaning, String> englishCol;
#FXML
private TableColumn<OvidhanMeaning, String> banglaCol;
#Override
public void initialize(URL location, ResourceBundle resources) {
Image search = new Image(getClass().getResource("/images/search.png").toString(), true);
Image about = new Image(getClass().getResource("/images/about.png").toString(), true);
//Font bnFont = Font.loadFont(getClass().getResource("/fonts/Siyamrupali.ttf").toExternalForm(), 12);
Font bnFont = Font.loadFont(getClass().getResourceAsStream("/fonts/Siyamrupali.ttf"), 12);
searchIcon.setImage(search);
aboutIcon.setImage(about);
db.Connect("jdbc:sqlite::resource:ankurdb/bn_words.db");
ResultSet rs = db.GetResult("select en_word,bn_word from words");
MeaningList=FXCollections.observableArrayList();
try {
while(rs.next())
{
String enword = rs.getString("en_word");
String bnword = rs.getString("bn_word");
MeaningList.add(new OvidhanMeaning(enword,bnword));
englishCol.setCellValueFactory(new PropertyValueFactory<OvidhanMeaning, String>("enword"));
banglaCol.setCellValueFactory(new PropertyValueFactory<OvidhanMeaning, String>("bnword"));
ovidhanTable.setItems(MeaningList);
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(MeaningList.size());
}
}
And here is my model class in which I loaded the data-
public class OvidhanMeaning {
private SimpleStringProperty enword;
private SimpleStringProperty bnword;
public OvidhanMeaning(String enword, String bnword) {
this.enword = new SimpleStringProperty(enword);
this.bnword = new SimpleStringProperty(bnword);
}
public String getenword() {
return enword.get();
}
public SimpleStringProperty enwordProperty() {
return enword;
}
public String getbnword() {
return bnword.get();
}
public SimpleStringProperty bnwordProperty() {
return bnword;
}
}
Now I'm trying to bind the searchField with the loaded MeaningList and populate the binded data into ovidhanTable.
How can I do this?
There is a class FXMLDocumentController.
There is a class ThreadForFile which has been inheriting from class Thread (which I read data from a file)
After I pressed the button (in the class FXMLDocumentController) I create a flow of class ThreadForFile.
I need to in the class ThreadForFile, when reading, the string displayed in the TextArea. But I can not figure out if I pass a parameter TextArea, and change it in the constructor, then there is a change in this component.But if I assign the class field this TextArea, it displays an error :
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
ThreadForFile extends Thread
private String path;
private long ms;
private int id;
private String name;
private boolean stop = false;
private HTMLEditor web;
private DB db = new DB();
private Button doc;
public void setMS(long ms){
System.out.print(ms);
this.ms =ms;
}
public ThreadForFile(String name,String path,long ms,int id,Button doc) {
this.path = new String();
this.path = path;
this.ms = ms;
this.id = id;
this.name = name;
this.doc = new Button();
this.doc = doc;
}
public void Stop(boolean stop){
this.stop = stop;
}
public void run( ) {
try {
doc.setText("Zsczsc");
System.out.print("asdasd");
File file = new File(path);
File file1 = new File("C:\\out.txt");
BufferedReader br = new BufferedReader (new InputStreamReader(new FileInputStream(file), "UTF-8"));
String line = null;
while( (line = br.readLine()) != null){
if(!Thread.interrupted()) //Проверка прерывания
{
if(!stop){
PrintWriter out = new PrintWriter(file1.getAbsoluteFile());
try {
sytem.out.print(line+"\n");
} finally {
out.close();
}
Thread.sleep(db.getParam().getMS()*1000);
System.out.print("ms" + db.getParam().getMS());
}
}else{
return;
}
}
} catch (Exception ex) {
System.out.print(ex.toString());
Logger.getLogger(ThreadForFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void read()throws FileNotFoundException, IOException
{
}
FXMLDocumentController
<!-- language: JavaFX -->
public class FXMLDocumentController implements Initializable {
private long ms = 5;
private ObservableList<ThreadForFile> threadForFile = FXCollections.observableArrayList();
private ObservableList<threadFile> threadFile = FXCollections.observableArrayList();
private int index ;
private DB db = new DB();
private Parametrs param = new Parametrs();
#FXML
private Button btnAdd;
#FXML
private Button btnStop;
#FXML
public Button btnDel;
#FXML
private Button btnStart;
#FXML
private TextField textFValueText;
#FXML
private TextField textFMs;
#FXML
private Button btnUpdate;
#FXML
public static TextArea textArea;
#FXML
private Label nameLabel;
#FXML
private Label pathLabel;
#FXML
private TextField textFName;
#FXML
private TextField textFPath;
#FXML
private TableColumn nameCol;
#FXML
private TableColumn pathCol;
#FXML
private TableColumn statCol;
public static FXMLDocumentController doc;
private ResourceBundle bundle;
#FXML
private TableView table;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
bundle = rb;
System.out.println("You clicked me!");
FileRead file = new FileRead(FXMLDocumentController.this);
Tab1();
Tab2();
Tab3();
param = db.getParam();
System.out.print(param.getMS() + " " + param.getValue());
}
public void Tab1()
{
}
public void Tab2()
{
//root.getChildren().addAll(btn,table,btnStop,btnStart,btnDel,nameField,pathField,name,path);
btnAdd.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
threadFile.add(new threadFile(textFName.getText(),textFPath.getText(),1));
threadForFile.add(new ThreadForFile(threadFile.get(threadFile.size()-1).getName(),threadFile.get(threadFile.size()-1).getPath(),ms,threadFile.size(),btnAdd));
threadForFile.get(threadForFile.size()-1).start();
index = table.getSelectionModel().getSelectedIndex();
System.out.print(index+ "\n");
}
});
.
.
.
.
.
.
.
.
.
.
}
You are trying to access a JavaFX Control outside the JavaFX Application thread.
Never use your controls, out of your Controller or pass them as a parameter to other methods. Instead, try to pass data to the controller, which in turn will set it to the controls inside the controller.
Some useful links are on passing data to the Controller :
Passing Parameters JavaFX FXML
How to have constructor with arguments for controller?
Some useful links on multi-threading in JavaFX:
How do I safely modify JavaFX GUI nodes from my own Thread?
JavaFX working with threads and GUI
I have a TableView with three TableColumns. There is an ObservableList named "sensorDataList " in MainApp.java that stores the objects to be shown in the TableView. With the following code, only the first TableColumn named "idColumn" doesn't show the values from the observable list, however, the other two TableColumns works fine.
MainApp.java (this has an "ObservableList" of Sensor objects (see Sensor.java). Also this class has the method named "showSensorDialog()" which loads the .fxml file that has the TableView in question. FYI, this method is invoked by a button in other controller.)
public class MainApp extends Application {
private Stage primaryStage;
private Stage sensorDialogStage;
private ObservableList<sensor> sensorDataList = FXCollections.observableArrayList();
public MainApp(){
sensorDataList.add(new sensor("testText","1 1 0.7", "0 0 1"));
}
public ObservableList<Sensor> getSensorDataList(){return sensorDataList;}
public void showSensorDialog() {
try {
FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("/view/SensorDialog.fxml"));
Object object = loader.load();
sensorDialogStage = new Stage();
Scene scene = new Scene((Parent) object);
sensorDialogStage.setScene(scene);
SensorDialogController controller = loader.getController();
controller.setSensorDialogStage(sensorDialogStage);
controller.setMainApp(this); // this line connects the ObservableList to the TableView.
sensorDialogStage.showAndWait();
} catch (IOException e) {}
}
}
SensorDialogController.java
public class SensorDialogController implements Initializable {
#FXML
private TableView<Sensor> sensorTable;
#FXML
private TableColumn<Sensor, String> idColumn;
#FXML
private TableColumn<Sensor, String> locationColumn;
#FXML
private TableColumn<Sensor, String> directionColumn;
private MainApp mainApp;
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
sensorTable.setItems(mainApp.getSensorDataList()); // ObservableList and TableView gets connected.
}
#Override
public void initialize(URL url, ResourceBundle rb){
idColumn.setCellValueFactory(new PropertyValueFactory<Sensor, String>("id"));
locationColumn.setCellValueFactory(new PropertyValueFactory<Sensor, String>("location"));
directionColumn.setCellValueFactory(new PropertyValueFactory<Sensor, String>("direction"));
}
}
Sensor.java
public class Sensor{
private SimpleStringProperty id;
private SimpleStringProperty location;
private SimpleStringProperty direction;
public Sensor(String i, String loc, String dir){
this.id = new SimpleStringProperty(i);
this.location = new SimpleStringProperty(loc);
this.direction = new SimpleStringProperty(dir);
}
}