如何使用JButton打开文件

时间:2015-03-21 18:44:06

标签: java jbutton

我有一个文件,我们可以称之为' example.txt'我已经在我的程序中调用了该文件。我想在单击JButton myButton时添加打开文件的功能。到目前为止,这是我的代码:

myButton.setText("Button");
 File example_file = new File("~/path/to/example.txt");
 myButton.addActionListener(new java.awt.event ActionListener(){
   public void actionPerformed (java.awt.event.ActionEvent evt){
     myButtonActionPerformed(evt);
   }
 });

private void myButtonActionPerformed(java.awt.event.ActionEvent evt){
   //open the file
}

我确定有一种非常简单的方法可以做到这一点,但我还没有找到任何东西。

2 个答案:

答案 0 :(得分:2)

Desktop.getDesktop().open(File file);

这可能会对您有所帮助:

Related Question and Answer.

答案 1 :(得分:1)

Desktop.getDesktop().open(new java.io.File("path to file"));

只是一个建议: 学习C \ C ++来完成这些工作。我做到了。

相关问题