设计:将未编组的JAXB对象绑定到JavaFX控件

时间:2014-06-09 10:16:10

标签: java model-view-controller jaxb javafx

我很难以正确的MVC方式实现我的目标:一个JavaFX应用程序,可以使用JAXB解析来自XML文件的票证,并显示xml文件中的一对多票证(使用一些文本框控件中的组合框或分页符。

MainWindowController(和fxml文件):

public class MainWindowController {
    // contains all the fxml controls
    private TicketAnalyzer ticketAnalyzer = new TicketAnalyzer();
    private List<TicketType> tickets = new ArrayList<TicketType>();

    @FXML
    private TextField txtNr1;
    //....
    @FXML
    private TextField txtNr5;

    private IntegerProperty nr1;
    //....
    private IntegerProperty nr5;

    @FXML
    protected void initialize(){     
        nr1 = new SimpleIntegerProperty(0);
        bind();
    }

    private void bind(){
        txtCurWinNr1.textProperty().bindBidirectional(nr1, new NumberStringConverter());
    }

    @FXML
    private void handleBtnEvaluateAction(ActionEvent event) {
        List<TicketType> tickets = ticketAnalyzer.evaluate(txtXMLPath.getText());
    if(tickets != null)
        this.tickets = tickets;

    updateTicket();
    }

    private void updateTicket(){
        if(this.tickets != null && this.tickets.size() > 0){
             nr1.set(tickets.get(0).getPlays().get(0).getNumbers().getNumber().get(0));         

        }
    }   
}

然后是'theticketAnalyzer'类:

public class TicketAnalyzer {

    private String xsdPath;

    public void loadXSD(String xsdPath){
    this.xsdPath = xsdPath;
}

    public void evaluate(String xmlPath){
        if(xsdPath.length() <= 0)
            return;

        if(!XMLValidator.validateXMLSchema(xsdPath, xmlPath)){
            System.out.println("THE XML file "+xmlPath+" is not valide agains "+xsdPath);
            System.exit(0);
        }

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance("jaxb.ticket");
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Source source = new StreamSource(new java.io.FileInputStream(xmlPath));

            JAXBElement<TicketsType> root = unmarshaller.unmarshal(source,TicketsType.class);
            TicketsType ticketsType = root.getValue();
            List<TicketType> tickets = ticketsType.getTicket();
            for (TicketType ticket : tickets) displayTicket(ticket);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

当我评估新的XML文件时,控制器中的本地票证列表会更新,当我更改属性值时,新值会根据需要显示在文本字段中。

我很不确定这种方法是否正确。嗯,它的工作,但感觉有点不对。特别是因为我必须使用许多数字来执行此操作并且必须能够选择票证(现在,0索引是硬编码的)甚至是票证内部的选择。

有没有更美丽的方式?我对整个Java和JavaFX世界都很陌生。

非常感谢!!

0 个答案:

没有答案