2012-11-16 29 views
-1

我正在使用JFileChooser,在按关闭按钮后不想关闭它。问题是,我按下关闭按钮后,会再次打开3次以上,最后关闭。JFileChooser不想关闭

我的代码:

javaButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    JFileChooser fileChooser = new JFileChooser(); 
    fileChooser.setDialogTitle("Save"); 

    int option = fileChooser.showSaveDialog(null); 
    if (option == JFileChooser.APPROVE_OPTION) { 
     String filename = fileChooser.getFileFilter().getDescription(); 
      try { 
       ChartUtilities.saveChartAsPNG(new File(filename), chart, getWidth(), getHeight()); 
       } catch (java.io.IOException exc) { 
       System.err.println("Error writing image to file"); 
       } 
    } 
    if (option == JFileChooser.CANCEL_OPTION) { 
       System.out.println("Task canceled!"); 
       //tried: fileChooser.setVisible(false); // >> same problem 

    } 
    } 
}); 

有什么建议?

+3

1)为了更好地帮助越早,张贴[SSCCE(http://sscce.org/)。 2)请为代码块使用一致的逻辑缩进。 –

+0

'if(option == JFileChooser.CANCEL_OPTION){'应该只是'else {'。 –

+0

这可能是也可能不是你的问题,但把你的右花括号放在与你的代码块相同的行上(参见catch块),或者将它们缩进到与花括号相同的位置{{(参见try块)非常混乱,并且很容易导致逻辑错误。相反,您可能会发现它更容易(我们一定会更清楚地理解您的代码),将'}'放在一行上,与块的开头对齐('try'中的字符't',例如)你打算关闭。 – dimo414

回答

2

如果选择有效,您在JFileChooser中选择的任何选项都会关闭对话框。

但是,请注意,if (option == JFileChooser.CANCEL_OPTION)下的代码将永远不会执行,因为您已经在评估option == JFileChooser.APPROVE_OPTIONtrue的分支内。

+0

括号现在已经关闭,但没有任何变化。对不起,当我在代码问题中提出代码时,我的错误。 –

+3

*“对不起,我的错误,”*而不是提供道歉,我宁愿看到你采取我的第一个建议(两点)采取行动。事实上,你已经有4个或更多的人通过不易阅读的代码追踪他们的尾巴,甚至可能甚至不包含问题代码。 –

0

我的建议是指定JFileChooser的父级,而不是将其设置为null。该对话的父母是什么?它是一个JFrame吗?

看看这个简单的例子,我相信它会为你工作。

http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

+0

*“我的建议是......”* ..使这个评论。 –

+0

确实。但我在这里是新的,直到我得到50的声誉,我不能添加评论给别人提出的问题。但你的指示是公平的。 – nikkatsa

+0

这不是要得到足够的代表。 –

0

试试这个:

javaButton.addActionListener(new ActionListener() { 
       public void actionPerformed(ActionEvent e) { 
       JFileChooser fileChooser = new JFileChooser(); 
       fileChooser.setDialogTitle("Save"); 

       int option = fileChooser.showSaveDialog(null); 
       if (option == JFileChooser.APPROVE_OPTION) { 
        String filename = fileChooser.getFileFilter().getDescription(); 
         try { 
          ChartUtilities.saveChartAsPNG(new File(filename), chart, getWidth(), getHeight()); 
          } catch (java.io.IOException exc) { 
          System.err.println("Error writing image to file"); } 
       } // here. 

       if (option == JFileChooser.CANCEL_OPTION) { 
          System.out.println("Task canceled!"); 

       } 
     }}); // one more }