代码适用于ide但不适用于从.jar运行

时间:2018-03-19 19:58:37

标签: java user-interface jar ide tess4j

制作这个小程序来测试一些GUI和Tess4j。

public static void main(String[] args) {

    JButton open = new JButton();
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new java.io.File("C:"));
    fc.setDialogTitle("Classificador de Documentos");
    if (fc.showOpenDialog(open) == JFileChooser.APPROVE_OPTION){

    }
    JFrame wait = new JFrame("Resultado");
    wait.setVisible(true);
    wait.setSize(300, 300);
    JLabel labelwait = new JLabel("Loading");
    JPanel panelwait = new JPanel();
    wait.add(panelwait);
    panelwait.add(labelwait);

    File imageFile = new File(fc.getSelectedFile().getAbsolutePath());
    ITesseract instance = new Tesseract();
    instance.setLanguage("por");// JNA Interface Mapping
    // ITesseract instance = new Tesseract1(); // JNA Direct Mapping

    try {
        String result = instance.doOCR(imageFile);

        if (result.toLowerCase().contains("ecocardiograma")){
            JFrame frame = new JFrame("Resultado");
            frame.setVisible(true);
            frame.setSize(300, 300);
            JLabel label = new JLabel("Este ficheiro é um ecocardiograma");
            JPanel panel = new JPanel();
            frame.add(panel);
            panel.add(label);
        }
        else {
            JFrame frame = new JFrame("Resultado");
            frame.setVisible(true);
            frame.setSize(300, 300);
            JLabel label = new JLabel("Este ficheiro não é um ecocardiograma");
            JPanel panel = new JPanel();
            frame.add(panel);
            panel.add(label);
        }
    } catch (TesseractException e) {
        JFrame frame = new JFrame("Resultado");
        frame.setVisible(true);
        frame.setSize(300, 300);
        JLabel label = new JLabel(e.getMessage());
        JPanel panel = new JPanel();
        frame.add(panel);
        panel.add(label);
    }
}

在Eclipse IDE上运行此代码时,它按预期工作,但在.jar文件上运行时,它会卡在标记为“正在加载”的第二帧上

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

如果您使用Swing解决方案是:

将您的代码放在线程安全

java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            // your main code ...
        }
    });

示例:

java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
           JFrame wait = new JFrame("Resultado");
           wait.setVisible(true);
           wait.setSize(300, 300);
           JLabel labelwait = new JLabel("Loading");
           JPanel panelwait = new JPanel();
           wait.add(panelwait);
           panelwait.add(labelwait);
        }
    });

如果您使用JavaFx解决方案是:

Platform.runLater(() -> {
        //your main code her ...
});

示例:

Platform.runLater(() -> {
        JFrame wait = new JFrame("Resultado");
        wait.setVisible(true);
        wait.setSize(300, 300);
        JLabel labelwait = new JLabel("Loading");
        JPanel panelwait = new JPanel();
        wait.add(panelwait);
        panelwait.add(labelwait);
});