Java第七次作业
(一)学习总结
1.写出事件处理模型中的几个关键词,并通过具体代码实例说明你对事件处理模型的理解。
一个图形界面制作完成了,但是在程序开发中这只是完成了起步的工作。因为想要让每一个组件都发挥起自己的作用,就必须对所有的组件进行时间处理。事件就是表示一个对象的发生状态变化。窗体事件中WindowListener是专门处理窗体的事件监听接口,其方法有:
void window Activated(WindowEvent e),
void window Deactivated(WindowEvent e),
void windowClosed(WindowEvent e),
void windowClosing(WindowEvent e),
void windowIconified(WindowEvent e),
void windowDeiconified(WindowEvent e),
void windowOpened(WindowEvent e)。
有了监听器还需要注册监听才可以处理,直接使用窗体的addWindowListener(监听对象)方法即可注册事件监听。关闭监听要用System.exit(1)语句,这样关闭按钮才真正起作用,让程序正常结束退出。监听适配器。匿名内部类。
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Win{
public static void main(String[] args){
JFrame f=new JFrame("welcome");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0){
System.exit(1);
}
})
f.setSize(300,160);
f.setLocation(300,200);
f.setVisible(true);
}
}
动作事件,ActionListener接口可以处理按钮的动作事件,方法:void actionPerformed(ActionEvent e)。instanceof关键字,可以用来判断操作的数据源类型,
if(arg[].getSource()instanceof JButton){
}
键盘事件,对键盘的操作进行监听,方法:KeyListener接口。对鼠标操作进行监听,方法:MouseListener接口。单选按钮,JRadioButton类的常用方法。
public char getKeyChar()
public int getKeyCode()
public static String getKeyText(int keyCode)
KeyAdapter
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javaxx.swing.JScrollPane;
import javax.swing.JTextArea;
class Key extends JFrame{
private JTextArea text=new JTextArea();
public Key(){
super.setTitle("Welcome");
JScrollPane scr=new JScrollPane(text);
scr.setBounds(5,5,300,300);
text.addKyeListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
text.append("输入的内容:"+e.getKeyChar()+"\n");
}
});
super.setSize(310,210);
super.setVisible(true);
super.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEven arg0){
System.exit(1);
}
}) ;
}
}
public class Key{
public static void main(String[] args){
new Key();
}
}
鼠标事件MouseListener接口的方法
void mouseCliked(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleassed(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
(二)实验总结
实验内容:
基本要求:
使用GUI,编写一个宠物商店管理系统实现对宠物信息的统一管理。假设宠物种类有猫、狗,宠物信息包括:编号、品种、年龄、数量、价格。系统启动进入登录界面,登录成功进入管理界面,否则提出错误信息后退出系统。
在管理界面实现以下功能:
(1)显示所有宠物列表
(2)添加宠物到列表
(3)删除宠物
(4)对宠物信息进行修改
(5)退出
实验思路:
建立宠物商店框体,设置其大小位置等数据,添加标签图片,布局管理器进行页面布局。文本组件绝对定位进行对宠物的添加删除等操作。还需要事件监听器窗体事件。参照老师的水果商店的程序。