我一直试图点击“帮助”按钮打开htmlfile
。我需要将文件导入源包,因此在构建后它不会显示错误。我正在使用netbeans
。当我将文件复制到src
并尝试运行该文件时,它在编译时显示错误。我想知道如何将文件添加到src
以及如何通过向用户询问系统中安装的浏览器列表来打开。这是我搜索过并试过的代码。谢谢提前
try
{
File htmlFile = new File(this.getClass().getResource("help.html").getFile());
Desktop.getDesktop().browse(htmlFile.toURI());
}
catch (IOException ex)
{
System.out.println(ex);
}
答案 0 :(得分:0)
我尝试使用My Desktop html
文件。现在它的工作正常。
它对你有用。(我的默认浏览器是chrome
)
试试吧。
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FileOpenBrowser {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("FileOpenBrowser"); // set API Name
JPanel topPanel = new JPanel(new FlowLayout()); // set Panel Layout
File urlDesktop = new File(
"C://Documents and Settings/Hariharan/Desktop/help.html");
Button btn = new Button("Help");
btn.setBounds(50, 100, 60, 30);
topPanel.add(btn);
frame.add(topPanel, BorderLayout.PAGE_START);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().open(urlDesktop);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}
答案 1 :(得分:0)
试试这个。
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FileOpenBrowser {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("FileOpenBrowser"); // set API Name
JPanel topPanel = new JPanel(new FlowLayout()); // set Panel Layout
Button btn = new Button("Help");
btn.setBounds(50, 100, 60, 30);
topPanel.add(btn);
frame.add(topPanel, BorderLayout.PAGE_START);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
System.out.println("Start..");
File file = new java.io.File("src/help.html").getAbsoluteFile();
Desktop.getDesktop().open(file);
System.out.println("End..");
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
}