javafx - 如何连接fx-controller和服务类

时间:2017-08-10 16:33:51

标签: java javafx

我正在处理个人应用程序并尝试使用javaFX。实际上我一直在连接控制器和服务。我们的想法是分离代码以获得更好的架构。我搜索了很多信息,但在我的案例中我无法找到正确的答案。如果有人有想法,我会很感激。

控制器

public class SettingsController extends AbstractController implements Initializable {

private final static Logger logger = LoggerFactory.getLogger(SettingsController.class);

@FXML
public TextField logFilepath;


@FXML
public TextField outputFilepath;

@FXML
private Button saveSettings;

/**
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    logger.debug("initialize");

    //do something
}

/**
 */
public void save() {
    logger.debug("save");

    final String logPath = logFilepath.getText();
    final String outputPath = outputFilepath.getText();

    System.out.println(logPath);

    settingService.save(logPath, outputPath);

    Stage stage = (Stage) saveSettings.getScene().getWindow();
    stage.close();      
}

settingService Interface

public interface SettingService {

/**
 */
void save(final String logPath, final String outputPath);

}

settingServiceImpl

public class SettingServiceImpl implements SettingService {

/**
 */
private static final Logger logger = LoggerFactory.getLogger(SettingServiceImpl.class);

/**
 */
public SettingServiceImpl() {
    super();
}

@Override
public void save(final String logPath, final String outputPath) {
    logger.debug("save");

    final Properties prop = new Properties();
    OutputStream output = null;

    try {
        output = new FileOutputStream("settings.properties");
        prop.setProperty("log_directory", logPath);
        prop.setProperty("output_directory", outputPath);
        prop.store(output, null);

    } catch (IOException io) {
        io.getMessage();

    } finally {
        if(output != null) {
            try {
                output.close();
            } catch (IOException iot) {
                iot.getMessage();
            }
        }
    }
}

}

AbstractController

public abstract class AbstractController {

/**
 */
protected SettingService settingService;

public AbstractController() {
    super();
}

}

当我运行我的应用程序时,它一直有效,直到我从我的控制器调用方法保存 - >我总是得到与NPE相同的错误

Caused by: java.lang.NullPointerException
at com.analyzer.controller.SettingsController.save(SettingsController.java:139)

如果我删除了保存方法' s参数 - > settingService.save(str,str) - 并用简单的字符串替换变量LogPath和outputPath,它可以工作..所以看起来我没有权利在控制器处理程序中调用带参数的方法。

值得!我想通过声明一个ServiceOut类来帮助我构建我的In和Out服务,但它有点复杂:(

0 个答案:

没有答案