为什么我必须将TextField声明为public,而不是Label

时间:2012-10-31 20:01:16

标签: java javafx

我是编程新手;放轻松。 :)

我有一个简单的程序(用于学习目的)除非我将两个TextField对象公开,否则将无法编译。我收到一个错误(ava.lang.IllegalAccessException:类javafx.fxml.FXMLLoader $ ValueElement无法使用修饰符“private”访问类firstjavafxprogram.SampleController的成员)。我只是不能为生活弄清楚为什么这两个人必须公开但Label可以是私人的。希望我正确发布我的代码:

package firstjavafxprogram;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

public class SampleController implements Initializable {

    @FXML
    private Label label;
    public TextField txtVolts;
    public TextField txtAmps;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        String labelMessage = getTheMessage();
        label.setText(labelMessage);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }  

   @FXML
    private String getTheMessage(){
        String enteredVolts = txtVolts.getText();
        int volts = Integer.parseInt(enteredVolts);

        String enteredAmps = txtAmps.getText();
        int amps = Integer.parseInt(enteredAmps);

        int watts = volts * amps;
        String msgString = "Watts: " + Integer.toString(watts);

        return msgString;
    }
}

1 个答案:

答案 0 :(得分:7)

更改

@FXML
private Label label;
public TextField txtVolts;
public TextField txtAmps;

@FXML
private Label label;
@FXML
private TextField txtVolts;
@FXML
private TextField txtAmps;

按此example