fileItem1是一个JMenuItem,这就是你打开一个文件的方式,然后在JFrame中显示该文件的名称:
// open file
fileItem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
Component parent = null;
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
}
jStyledTextPane.setText("You chose to open this file: " + chooser.getSelectedFile().getName());
}
});
答案 0 :(得分:1)
fileItem1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(YourClassName.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
filePath = file.getAbsolutePath();
try {
//your write to Jframe method
} catch (FileNotFoundException e) {
Logger.getLogger(YourClassName.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
});
答案 1 :(得分:0)
在我看来,Oracle示例相当不错:http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
以下是实施:
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
} else {
log.append("Open command cancelled by user." + newline);
}