1、事件处理
(1)、键盘事件及监听处理
在Swing的事件处理中也可以对键盘的操作进行监听,直接使用KeyListener接口即可。此接口定义了如下的方法。
如果要想取得键盘键入的内容,则可以通过KeyEvent取得,此类的常用方法如下所示。
实例:
package work10;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class mykeyhandle implements KeyListener{
JFrame frame;
JScrollPane scpane;
JTextArea area;
public mykeyhandle() {
frame=new JFrame("键盘事件处理");
area=new JTextArea();
scpane=new JScrollPane(area);
area.addKeyListener(this);
frame.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
frame.add(scpane);
frame.setSize(600,450);
frame.setLocation(400, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
new mykeyhandle();
}
@Override
public void keyTyped(KeyEvent e) {
area.append("键入"+KeyEvent.getKeyText(e.getKeyCode())+"键"+"
");
}
@Override
public void keyPressed(KeyEvent e) {
area.append("按下"+KeyEvent.getKeyText(e.getKeyCode())+"键"+"
");
}
@Override
public void keyReleased(KeyEvent e) {
area.append("松开"+KeyEvent.getKeyText(e.getKeyCode())+"键"+"
");
}
}
运行截图
(2)、鼠标事件及监听处理
如果想对一个鼠标的操作进行监听,例如,鼠标按下、松开等,则可以实现MouseListener接口
在每个事件触发后都会产生MouseEvent事件,此事件可以得到鼠标的相关操作
在一般的图形界面中经常可以看到鼠标拖拽操作的情况,在Swing的事件处理中可以使用MouseMotionListener接口可以完成鼠标的拖拽操作
实例
package work10;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class MyMouseHandle extends JFrame implements MouseListener {
private JTextArea text = new JTextArea();
public MyMouseHandle() {
super.setTitle("鼠标事件处理");
JScrollPane pane = new JScrollPane(text);
pane.setBounds(5, 5, 300, 200);
super.add(pane);
text.addMouseListener(this);
super.setSize(310, 210);
super.setVisible(true);
super.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
System.exit(1);
}
});
}
public void mouseClicked(MouseEvent e)
{
int c = e.getButton();
String mouseInfo = null;
if (c == MouseEvent.BUTTON1)
{
mouseInfo = "左键";
} else if (c == MouseEvent.BUTTON3) {
mouseInfo = "右键";
} else {
mouseInfo = "滚轴";
}
text.append("鼠标单击:" + mouseInfo + ".
");
}
public void mouseEntered(MouseEvent e)
{
text.append("鼠标进入组件.
");
}
public void mouseExited(MouseEvent e)
{
text.append("鼠标退出组件.
");
}
public void mousePressed(MouseEvent e)
{
text.append("鼠标按下.
");
}
public void mouseReleased(MouseEvent e)
{
text.append("鼠标松开.
");
}
}
public class MyMouseEventDemo {
public static void main(String[] args) {
new MyMouseHandle();
}
}
运行截图
2、菜单组件
(3)、文件选择框JFileChooser