[英]JFileChooser to open a file from a JMenu
當我單擊fileItem1時,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());
}
});
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);
}
}
}
});
在我看來,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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.