javaFX与spring整合方法

目前在用JavaFx与spring结合做一个客户端程序,把javaFx的视图对应的controller交给spring管理,方法如下:

public class SpringFxmlLoader extends FXMLLoader{


private static  ApplicationContext applicationContext = null;


@SuppressWarnings("rawtypes")
public  Object springLoad(String url,Class cl) throws Exception{
applicationContext = StaticData.context;
 try  {
 InputStream fxmlStream = cl.
   getResourceAsStream(url);
  FXMLLoader loader = this;
  loader.setControllerFactory(new Callback, Object>() {
   @Override
   public Object call(Class clazz) {
    return applicationContext.getBean(clazz);
   }
  });
  return loader.load(fxmlStream);
 } catch (IOException ioException) {
  throw new RuntimeException(ioException);
 }
}
}

其中,ApplicationContext  是spring的上下文,可以通过context = new ClassPathXmlApplicationContext(   new String[] { "classpath:applicationContext.xml" });

等方式获取。

下面是调用的生成controller的代码

Stage stage = new Stage();

AnchorPane root = null;
SpringFxmlLoader loader = new SpringFxmlLoader();
try {
root = (AnchorPane) loader.springLoad("view/TableView.fxml", Main.class);
 TableController controller = loader.getController();
controller.setStage(stage); 
 Scene scene = new Scene(root);
 stage.setScene(scene); 
stage.show(); 
stage.setTitle("这是一个标题");
} catch (Exception e) {
e.printStackTrace();
DialogTools.error("错误", "出错了!", "查询表单数据出错!");
}

 

你可能感兴趣的:(javaFX)