本帖最后由 Sunshine0308 于 2015-6-27 13:28 编辑
/*
* 创建图形化界面
* 1.创建frame窗口
* 2.对窗口进行基本设置,比如大小setSize(int,int),位置setLocation(int,int),布局 setLayout(LayoutManager mgr)
* 3.定义组件
* 4.将组件通过窗口的add方法添加到窗体中
* 5.让窗体显示f.setVisible(true)
* */
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MyWindow
{
private Frame f;
private TextField tf;
private Button b ,bu;
private TextArea ta;
private Dialog d;
private Label la;
MyWindow()
{
init();
}
private void init()
{
f=new Frame("我的窗口");
f.setSize(600,500);
f.setLocation(300,200);
f.setLayout(new FlowLayout());
tf=new TextField(60);
b=new Button("转到");
ta=new TextArea(25,70);
f.add(tf);
f.add(b);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
//System.out.println("hahahaha");
showDir();
}
});
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showDir();
}
});
bu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
//System.out.println("hahahaha");
}
});
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
//System.out.println("hahahaha");
}
});
}
private void showDir()
{
String dirPath=tf.getText();
File dir=new File (dirPath);
if(dir.exists()&&dir.isDirectory())
{
ta.setText("");
String[] names=dir.list();
for(String name:names)
{
ta.append(name+"\r\n");
}
}
else
{
d=new Dialog(f,"Mywindow资源管理器",true);
d.setBounds(300,200,250,100);
d.setLayout(new FlowLayout());
la=new Label();
bu=new Button("确定");
d.add(la);
d.add(bu);
String info="Mywindow找不到"+"“"+dirPath+"”"+"."+"请检查拼写并重试";
la.setText(info);
d.setVisible(true);
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
new MyWindow();
}
}
提示:
Exception in thread "main" java.lang.NullPointerException
at MyWindow.myEvent(MyWindow.java:70)
at MyWindow.init(MyWindow.java:37)
at MyWindow.<init>(MyWindow.java:22)
at MyWindow.main(MyWindow.java:121)
|
|