有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java绑定双值到JavaFXGUI

我已经为我的学校项目(调谐器)实现了fft,尽管我无法将计算出的频率传递给GUI。我试过绑定,关键帧,我似乎无法掌握它,我对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;
}

这是我的控制器的一部分,我还被建议使用一种叫做紧绑定的东西,这就是这个类的抽象。这对我的代码有好处吗

这是我的主控制器:

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());
}

共 (1) 个答案

  1. # 1 楼答案

    将FrequencyBean正确地重写为“javafxbean”:

    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;
       }
    }
    

    正如Jame_D指出的:不要初始化带有@FXML注释的控件。 只需像这样绑定有问题的控件:

    ...
    @FXML 
    TextField tf_Frequency;
    ...
    
    fbean = new FrequencyBean(20.3);
    tfFrequency.textProperty().bind(fbean.frequencyProperty().asString("%.2f"));
    

    请注意,如果需要单向绑定,这是正确的。 还有一种方法