gpt4 book ai didi

java - JFileChooser 从 JMenu 打开文件

转载 作者:行者123 更新时间:2023-12-01 14:45:10 26 4
gpt4 key购买 nike

当我点击 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);
}

}
}
});

关于java - JFileChooser 从 JMenu 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15498709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com