黑马程序员+对Java中匿名内部类总结

时间:2022-10-01 00:48:31

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

  在学习图形化界面时,我发现监听机制中事件处理时用到匿名内部类,感觉在前面的基础学习中也用到过,我又回去查了一下,果然在Java面向对象中出现过,为此我用思维导图及代码对匿名内部类作了一些总结,由于本人能力有限。可能会有一些不完善或错误的地方,敬请指正,谢谢!

黑马程序员+对Java中匿名内部类总结

图1 匿名内部类

黑马程序员+对Java中匿名内部类总结

图2 匿名内部类使用情况

黑马程序员+对Java中匿名内部类总结

图3 匿名内部类原则

匿名内部类实例

public class GUI {
private Frame frame;
private Panel panel1;
private Panel panel2;
private Button start;
private Button ret;
private Button set;
private Dialog dialog;
private Button ok;

public static void main(String[] args) {
// TODO Auto-generated method s
new GUI();
}
//创建图形化界面
GUI(){
frame=new Frame("萍");
frame.setBounds(900, 200, 300, 400);
panel1=new Panel();
panel1.setBackground(Color.RED);
panel2=new Panel();
panel2.setBackground(Color.BLUE);
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
panel1.setLayout(new FlowLayout());
start=new Button("开始");
start.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dialog=new Dialog(frame,"游戏开始",true);
dialog.setLayout(new FlowLayout());
dialog.setBounds(800, 400, 100, 100);
ok=new Button("确定");
dialog.add(ok);
dialog.addWindowListener(new WindowAdapter(){//匿名内部类
public void windowClosing(WindowEvent e){
dialog.setVisible(false);
}
});
ok.addActionListener(new ActionListener(){//匿名内部类
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dialog.setVisible(false);
}});
dialog.setVisible(true);
}

});
//可见性必须最后设置
ret=new Button("返回");
ret.addActionListener(new ActionListener(){//匿名内部类

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("返回");
}
});
set=new Button("设置");
set.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("设置");
}
});
panel1.add(start);
panel1.add(ret);
panel1.add(set);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});//注册事件监听器
frame.setVisible(true);
}

}

运行结果

黑马程序员+对Java中匿名内部类总结