I have implemented fft for my school project(tuner), although, im not able to pass calculated frequency to GUI. I tried binding, keyframes, i just cant seem to get a grasp of it, im really new to java.
public class FrequencyBean {
double freq;
private SimpleDoubleProperty value = new SimpleDoubleProperty(this, "value");
public void setValue(double value){
this.value.set(value);
System.out.println(value+" set");
}
public DoubleProperty getDoublePropertyValue(){
System.out.println("gotvals");
return value;
}
public FrequencyBean(){
freq = 10.0;
}
that is part of my controller, also i got reccomended to use something called tight binding or so, which would be abstracting of this class. Is that good for my code?
This is my main controller:
public class Controller implements Initializable{
FrequencyBean fbean;
#FXML
private Label otherFq;
#FXML
private Text frequency;
#FXML
private Text sharpFq;
#FXML
private Rectangle sharp6;
#FXML
private Text flatFq;
#FXML
private Rectangle center_rectangle;
#FXML
private Rectangle sharp1;
#FXML
private Rectangle sharp2;
#FXML
private Rectangle sharp3;
#FXML
private Rectangle sharp4;
#FXML
private Rectangle sharp5;
#FXML
private Text centerFq;
#FXML
private Rectangle flat6;
#FXML
private Rectangle flat5;
#FXML
private Rectangle flat4;
#FXML
private Rectangle flat3;
#FXML
private Rectangle flat2;
#FXML
private Rectangle flat1;
#Override
public void initialize(URL location, ResourceBundle resources) {
fbean = new FrequencyBean();
otherFq = new Label();
frequency = new Text();
boolean stop = false;
InputThread input = new InputThread();
Task<Void> in = new Task<Void>() {
#Override
protected Void call() throws Exception {
input.run();
return null;
}
};
Thread th0 = new Thread(in);
th0.start();
frequency.textProperty().bind(fbean.getDoublePropertyValue());
}
Rewrite your FrequencyBean correctly as a 'JavaFX-Bean':
public class FrequencyBean {
private SimpleDoubleProperty frequency = new SimpleDoubleProperty();
/**
* #param frequency the frequency to set
*/
public void setFrequency(double value){
this.frequency.set(value);
}
/**
* #return the frequency as double
*/
public double getFrequency(){
return this.frequency.get();
}
/**
* #return the frequency property
*/
public DoubleProperty frequencyProperty(){
return value;
}
public FrequencyBean(){
frequency = 10.0;
}
}
As Jame_D pointed it out: don't initialize a control annotated with #FXML.
Just bind the control in question like so:
...
#FXML
TextField tf_Frequency;
...
fbean = new FrequencyBean(20.3);
tfFrequency.textProperty().bind(fbean.frequencyProperty().asString("%.2f"));
Note that this is correct if you need a uni-directional binding.
There is also a bindBidirectional method.
Related
I have to set values for labels, I am set values by following way which is very lengthy,
public class FXMLDocumentController implements Initializable {
private TilesLogic gl = new TilesLogic();
private List<List<Integer>> game;
#FXML
private Label C1;
#FXML
private Label C2;
#FXML
private Label C3;
#FXML
.
.
.
private Label C16;
#FXML
private Label timer;
#Override
public void initialize(URL url, ResourceBundle rb) {
game = gl.shuffle();
SetValues();
}
void SetValues(){
C1.setText(String.valueOf(game.get(0).get(0)));
C2.setText(String.valueOf(game.get(0).get(1)));
.
.
C15.setText(String.valueOf(game.get(3).get(2)));
C16.setText(String.valueOf(game.get(3).get(3)));
}
}
is that any other way just like that
for(int i =1;i<17;i++)
setText("#C"+String.valueOf(i),String.valueOf(game.get(i)));
// setText("#id","Sometext");
to do it simple way and less time ?
I am a newbie in Javafx and I am trying to fix a cropping over an image. I found an interesting solution for cropping with rubber band and now I try to modified this in my scenario.
I have two controllers. One controller has the crop button (CropController) and another controller which contain an image as ImageController.
CropController:
public class CropController {
#FXML
private void initialize() {}
#FXML
private void handleCrop(){
}
}
ImageController:
public class ImageController {
#FXML
private ImageView MainImage;
#FXML
private void initialize() {
modelSharedOne.imageProperty()
.addListener((obs, oldImage,newImage)-> MainImage.setImage(newImage));
}
#FXML
private void handleMousePresses(){}
#FXML
private void handleMouseDragged(){}
#FXML
private void handleMouseReleased(){}
}
Based on the rubber band solution I need to group those three mouse handlers. I do not know what could be the best solution for this. I have tried many solutions like creating a model between these two controllers but I have not managed to solve this solution.
Anyone knows how can I solve this?
My current solution
CropController:
public class ToolboxController {
#FXML
private void initialize() {
}
#FXML
private void handleCrop(){
SharedModelTwo.callHandlerInWorkstation();
}
}
SharedModelTwo:
public class CropImageModel {
ImageController imageController;
public void callHandlerInImage(){
imageController = new ImageController();
imageController.handleCrop();
}
}
ImageController:
public class ImageController {
#FXML
private ImageView MainImage;
#FXML
private void initialize() {
modelSharedOne.imageProperty()
.addListener((obs, oldImage,newImage)-> MainImage.setImage(newImage));
}
public void handleCrop() {
Image image = getImage();
ImageView imageView = new ImageView(image);
rect = new Rectangle( 0,0,0,0);
rect.setStroke(Color.BLUE);
rect.setStrokeWidth(1);
rect.setStrokeLineCap(StrokeLineCap.ROUND);
rect.setFill(Color.LIGHTBLUE.deriveColor(0, 1.2, 1, 0.6));
Group imageLayer = new Group();
imageLayer.getChildren().add(imageView);
rubberBandSelection = new RubberBandSelection(imageLayer);
}
}
And rubberBandSelection is a class as it was in the linked. when I run that it does not hit when mouse pressed on image.
I've been trying to create a music player and part of that requires listening to a time slider. So I've added to the time slide and this is the error I get:
I've been trying to get my head around how you fix this error and the whole business of overriding.
Can anyone point me in the right direction on how to fix this error?
My Code:
public class graphicalController implements Initializable
{
//GUI Decleration
#FXML
public Button centreButton;
#FXML
public Button backButton;
#FXML
public Button forwardButton;
#FXML
public ToggleButton muteToggle;
#FXML
public MenuItem loadFolder;
#FXML
public Text nameText;
#FXML
public Text albumText;
#FXML
public Text timeText;
#FXML
public Text artistText;
#FXML
public Slider timeSlider;
#FXML
public Slider volumeSlider;
//Controller Decleration
String absolutePath;
SongQueue q = new SongQueue();
MediaPlayer player;
Status status;
boolean isPlaying = false;
boolean isMuted = false;
boolean isPaused = false;
private Duration duration;
/**
* The constructor. The constructor is called before the initialize()
* method.
*
* Anything in regards to CSS styling with FXML MUST be done within the initialize method.
*/
public graphicalController() {
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
public void initialize(URL location, ResourceBundle resources)
{
centreButton.setStyle("-fx-background-image: url('/Resources/Play_Button.png')");
centreButton.setText("");
backButton.setStyle("-fx-background-image: url('/Resources/Back_Button.png')");
backButton.setText("");
forwardButton.setStyle("-fx-background-image: url('/Resources/Forward_Button.png')");
forwardButton.setText("");
muteToggle.setStyle("-fx-background-image: url('/Resources/ToggleSound_Button.png')");
muteToggle.setText("");
nameText.setText("");
albumText.setText("");
artistText.setText("");
volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
double sliderValue = newValue.intValue();
handleVolumeSlider(sliderValue);
}
});
timeSlider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
//outputTextArea.appendText("Slider Value Changed (newValue: " + newValue.intValue() + ")\n");
}
});
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
// multiply duration by percentage calculated by slider position
if(duration!=null) {
player.seek(duration.multiply(timeSlider.getValue() / 100.0));
}
updateValues();
}
}
});
}
public void setSongText() {
String file = q.peek().fileName;
String songName = q.peek().songName;
String albumName = q.peek().albumName;
String artistName = q.peek().artistName;
if (songName == "") {
songName = "Song name not specified in metadata.";
}
else if (albumName == "")
{
albumName = " Album name not specified in metadata.";
}
else if (artistName == "")
{
artistName = "Artist name not specified in metadata.";
}
nameText.setText(songName);
albumText.setText(albumName);
artistText.setText(artistName);
}
}
You will find my problem in the initialize method.
Are you using the correct Observable type? It should be of type javafx.beans.Observable.
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);
}
}