继我之前的帖子 in this link我有另一个问题。
给定以下代码:
public class GuiHandler extends javax.swing.JFrame {
// GuiHandler is the class that runs the entire project
// here are two private fields that I use in the code , I have more but they
// irrelevant for the moment
final JFileChooser openFiles = new JFileChooser();
private DataParser xmlParser = new DataParser();
// later on I have this method - XMLfilesBrowserActionPerformed
private void XMLfilesBrowserActionPerformed(java.awt.event.ActionEvent evt) {
//setting the file chooser
openFiles.setFileSelectionMode(JFileChooser.FILES_ONLY);
openFiles.setAcceptAllFileFilterUsed(false);
if (openFiles.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
//getting the selected file
File selected = openFiles.getSelectedFile();
// from here I parse the XML file that I opened with JFileChooser
// with the help of one of my methods getNodeListFromFile
xmlParser.getNodeListFromFile(selected);
问题是我不能使用之前在上面的链接中建议的 main
的声明(我必须补充说这是一个非常好的:)),发布的代码是:
public class NativeFileChooser {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
}
});
}
}
main
的使用使得以后使用我的 XML
文件变得非常困难
方法 getNodeListFromFile
.
我需要的是使用 JFileChooser
的“简单”浏览器,然后使用所选文件,而不涉及 main
。
如果有人能解释我如何在我的代码中使用上述代码(或其他任何代码),我将不胜感激。
最好的问候
编辑:
如果我使用这样的代码;
public void launchFileChooser() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
newFile = jfc.getSelectedFile();
}
});
}
这里的newFile
是一个数据成员。
打开文件后,代码崩溃。
如果我使 jfc
成为数据成员,代码将打开常规浏览器。知道如何解决吗?
谢谢
最佳答案
我确信代码只是一个独立的示例。
您应该以某种方式将 JFileChooser
工作到您的 GuiHandler
中。如果有的话,您可以将该代码添加到 GuiHandler
public class GuiHandler extends javax.swing.JFrame {
//lots of your other code
public void launchFileChooser() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
}
});
}
public static void main(String[] args) {
GuiHandler handler = new GuiHandler();
handler.launchFileChooser();
}
}
关于java - 在不使用 main 声明的情况下使用 JFileChooser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907738/