java - 如何使用 JButton 打开文件

标签 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
}

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

最佳答案

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

这可能对您有帮助:

Related Question and Answer.

关于java - 如何使用 JButton 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29186609/

相关文章:

java - 多模块 Maven 项目!无法将模块作为依赖项包含在同一项目的另一个模块中

java - JButton 的颜色

java - 为什么打开网页的 JButton 仅在第一次单击时起作用,然后被停用?

java - 使用 ActionListeners 并且无法将文本字段设置为不可见

java - hapi-fhir 将 fhir 对象转换为 json 字符串

Java.util.zip 替换单个 zip 文件

java - 将语言配置文件添加到 Apache Tika

java - JSF 2 DI 与 CDI Java EE 6/7

java - 检测 JButton 中的文本溢出

java - 我怎样才能获得按钮的来源并让它发挥作用?