- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- class MyWindowDemo
- {
- private Frame f;
- private TextField tf;
- private Button but;
- private TextArea ta;
- private Dialog d;
- private Label lab;
- private Button lbut;
- MyWindowDemo()
- {
- init();
- }
- public void init()
- {
- f = new Frame("my window");
- f.setBounds(300,100,500,400);
- f.setLayout(new FlowLayout());
- tf = new TextField(30);
- but = new Button("提交");
- ta = new TextArea(15,40);
- f.add(tf);
- f.add(but);
- f.add(ta);
- myEvent();
- f.setVisible(true);
- }
- public void myEvent()
- {
- but.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ta.setText("");
- String dirPath = tf.getText();
- File dir = new File(dirPath);
- if(dir.exists() && dir.isDirectory())
- {
- String[] names = dir.list();
- for(String name :names)
- {
- ta.append(name+"\r\n");
- //sop(name);
- }
- } else
- {
- sop("sdas");
- d = new Dialog(f,"lallalalalal",true);
- lab = new Label("-------fail--------");
- lbut = new Button("ok");
- d.setBounds(400,200,500,100);
- d.setLayout(new FlowLayout());
- d.add(lab);
- d.add(lbut);
- d.setVisible(true);
- }
- }
- });
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- ta.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- e.consume();
- }
- });
- /* 从这里往下再运行时,具体说是初始化的时候就已经报空指针异常
- d.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- d.setVisible(false);
- }
- });
- lbut.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- d.setVisible(false);
- }
- });
- */
- }
- public static void main(String[] args)
- {
- new MyWindowDemo();
- }
-
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 因为毕老师视频里把创建对话框对象的代码写在了init()里面,但是他在视频中也说到了,为了节省内存空间,可以把创建对象放到,触发事件之后,我是这么理解的,所以把代码放到了else{}里面,但是在myEvent()中,显然在初始化时还没有创建Dialog的对象,所以出现了空指针异常,我想知道这种情况一般都是如何解决的
即能节省内存,又可以躲开空指针异常
我想到一个办法,但是失败了
if(d!=null)
{
再触发新的事件
}
因为这些是在初始化的时候加载到监听机制中的,所以d对象为空的时候已经跳过了这些代码
|