标签:bin ESS bubuko set stat 事件传递 type color 机制



































x
实例[Window016.java]/*** 功能:事件处理机制*/import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Window016 extends JFrame implements ActionListener{ //定义组件 JPanel mp=null; JButton jb1,jb2; public static void main(String[] args) { Window016 win=new Window016(); } //构造函数 public Window016(){ //创建组件 mp=new JPanel(); jb1=new JButton("黑色"); jb2=new JButton("红色"); //设定布局管理器 //加入组件 mp.setBackground(Color.black); this.add(mp); this.add(jb1,BorderLayout.NORTH); this.add(jb2,BorderLayout.SOUTH); //猫类在监听 Cat mycat1=new Cat(); jb1.addActionListener(mycat1); jb2.addActionListener(mycat1); //注册监听 jb1.addActionListener(this); jb2.addActionListener(this); //指定action命令 jb1.setActionCommand("黑色"); jb2.setActionCommand("红色"); //JFrame窗体设置 this.setTitle("事件处理机制"); this.setSize(400, 300); this.setLocationRelativeTo(null); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //对事件处理的方法 public void actionPerformed(ActionEvent e) { //判断是哪个按钮被点击 if(e.getActionCommand().equals("黑色")){ System.out.println("点击了黑色按钮"); mp.setBackground(Color.BLACK); }else if(e.getActionCommand().equals("红色")){ System.out.println("点击了红色按钮"); mp.setBackground(Color.RED); }else{ System.out.println("不知道"); } }}class Cat implements ActionListener{ public void actionPerformed(ActionEvent arg0) { if(arg0.getActionCommand().equals("黑色")){ System.out.println("Cat也知道你按下了黑色按钮"); }else if(arg0.getActionCommand().equals("红色")){ System.out.println("Cat也知道你按下了红色按钮"); }else { System.out.println("Cat也不知道"); } }}实例[Window017.java]/*** 功能:加深对事件处理机制的理解* 1、通过上下左右键,来控制一个小球的移动。*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Window017 extends JFrame { //设定组件 MyPanels mp=null; public static void main(String[] args) { Window017 win=new Window017(); } //构造函数 public Window017(){ //构建组件 mp=new MyPanels(); //监听 this.addKeyListener(mp); //加入组件 this.add(mp); //设置窗体 this.setTitle("键盘事件监听"); this.setSize(400, 300); this.setLocationRelativeTo(null); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}//定义自己的面板class MyPanels extends JPanel implements KeyListener{ int x=10,y=10; public void paint(Graphics g){ super.paint(g); g.fillOval(x, y, 10, 10); } public void keyPressed(KeyEvent e) {//keyPressed代表键被按下 System.out.println("被按下"+((char)e.getKeyCode())); if(e.getKeyCode()==KeyEvent.VK_DOWN){ System.out.println("向下"); y++; }else if(e.getKeyCode()==KeyEvent.VK_UP){ System.out.println("向上"); y--; }else if(e.getKeyCode()==KeyEvent.VK_LEFT){ System.out.println("向左"); x--; }else if(e.getKeyCode()==KeyEvent.VK_RIGHT){ System.out.println("向右"); x++; } //调用repaint()函数,来重绘界面 this.repaint(); } public void keyReleased(KeyEvent e) {//keyReleased代表键被弹起 } public void keyTyped(KeyEvent e) {//keyTyped代表具体的值被输出 }
标签:bin ESS bubuko set stat 事件传递 type color 机制
原文地址:https://www.cnblogs.com/xuxaut-558/p/10045724.html