import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;public class ExampleFrame_09 extends JFrame { private JTextField textField; public static void main(String args[]) {
ExampleFrame_09 frame = new ExampleFrame_09();
frame.setVisible(true);
} public ExampleFrame_09() {
super();
setTitle("文件选择对话框");
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH); final JLabel label = new JLabel();
label.setText("文件:");
panel.add(label); textField = new JTextField();
textField.setColumns(20);
panel.add(textField); final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int i = fileChooser.showOpenDialog(ExampleFrame_09.this);
if (i == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
textField.setText(selectedFile.getName());
}
}
});
button.setText("上传");
panel.add(button);
//
}
}int i = fileChooser.showOpenDialog(ExampleFrame_09.this);43行,这句,如果改成
int i = fileChooser.showOpenDialog(this);为何就不对了?this不就是ExampleFrame_09的引用吗?和上面不是一个效果?java基础this

解决方案 »

  1.   

    你这个是匿名内部类fileChooser.showOpenDialog(this); 指的是new ActionListener()。
     fileChooser.showOpenDialog(ExampleFrame_09.this);才指的是ExampleFrame_09。
      

  2.   

    int i = fileChooser.showOpenDialog(ExampleFrame_09.this)这句话是在这里相当于是匿名类 ActionListener类里面的一句话,是如果直接用this,这个this就是相当于ActionListener这个类,而消息框是要显示在ExampleFrame_09这个Frame里的,所以需要用ExampleFrame_09.this
      

  3.   

    new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser fileChooser = new JFileChooser();
                    int i = fileChooser.showOpenDialog(ExampleFrame_09.this);
                    if (i == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        textField.setText(selectedFile.getName());
                    }
                }
            });虽然这个类没有名字,但是也是实现了new ActionListener()接口的一个类,因为没有名,就叫匿名内部类。。
    这里的this指的是这个类。