1 public static void main(String[] args) { 2 JFrame frame = new JFrame(); 3 JButton button = new JButton("上传"); 4 frame.add(button); 5 frame.setVisible(true); 6 button.addActionListener(new ActionListener() { 7 public void actionPerformed(ActionEvent e) { 8 // 按钮点击事件 9 10 JFileChooser chooser = new JFileChooser(); // 设置选择器 11 chooser.setMultiSelectionEnabled(false); // 设为单选 12 int returnVal = chooser.showOpenDialog(button); // 是否打开文件选择框 13 System.out.println("returnVal=" + returnVal); 14 15 if (returnVal == JFileChooser.APPROVE_OPTION) { // 如果符合文件类型 16 17 String filepath = chooser.getSelectedFile().getAbsolutePath(); // 获取绝对路径 18 System.out.println(filepath); 19 20 System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); // 输出相对路径 21 22 } 23 } 24 }); 25 }