黑马程序员技术交流社区
标题:
为对话框添加键盘监听事件
[打印本页]
作者:
ifuzhen
时间:
2014-5-3 15:54
标题:
为对话框添加键盘监听事件
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class MyWindowDemo
{
private Frame f;
private TextField tf;
private Button btn;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okBtn;
MyWindowDemo()
{
init();
}
public void init()
{
f=new Frame("my window");
f.setBounds(300,300,500,300);
f.setLayout(new FlowLayout());
tf =new TextField(60);
btn =new Button("go");
ta =new TextArea(60,60);
d =new Dialog(f,"my-提示对话框",true);
d.setBounds(400,300,200,150);
d.setLayout(new FlowLayout());
lab=new Label("",Label.RIGHT);
d.add(lab);
okBtn=new Button("确定");
d.add(okBtn);
f.add(tf);
f.add(btn);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showDir();
}
});
//添加按键盘的回车键,注意现在事件源为文本框
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)//注意方法名写错是不会报错的
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
showDir();
}
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
sop("fram-window exit");
}
});
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
okBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
//为何不起作用呢?
d.addKeyListener(new KeyAdapter()
{
public void KeyPressed(KeyEvent e)
{
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
d.setVisible(false);
}
}
});
}
public 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
{
String info="找不到目录:"+dir+",请重新输入";
lab.setText(info);
d.setVisible(true);
}
}
public static void main(String[] args)
{
new MyWindowDemo();
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
复制代码
想要的效果就是当弹出一个带有"确定按钮"的对话框时,当回车时对话框会消失,可是给对话框添加了键盘监听事件,好像不起作用呢?
QQ截图20140503155335.png
(10.49 KB, 下载次数: 32)
下载附件
2014-5-3 15:54 上传
对话框
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2