16.3

 1 import java.awt.BorderLayout;
 2 import java.awt.Graphics;
 3 import java.awt.event.ActionEvent;
 4 import java.awt.event.ActionListener;
 5 import java.awt.event.ComponentEvent;
 6 import java.awt.event.ComponentListener;
 7 
 8 import javax.swing.JButton;
 9 import javax.swing.JFrame;
10 import javax.swing.JPanel;
11 
12 public class Test_16 extends JFrame implements ActionListener{
13     private JButton j1 = new JButton("left");
14     private JButton j2 = new JButton("right");
15     private JButton j3 = new JButton("up");
16     private JButton j4 = new JButton("down");
17     private JP j = new JP();
18     private int x =100,y =200;
19     
20     public Test_16(){
21         JPanel J = new JPanel();
22         J.add(j1);J.add(j2);J.add(j3);J.add(j4);
23         j1.addActionListener(this);
24         j2.addActionListener(this);
25         j3.addActionListener(this);
26         j4.addActionListener(this);
27         add(J,BorderLayout.SOUTH);
28         add(j,BorderLayout.CENTER);
29     }    
30     
31     public static void main(String[] args) {
32         // TODO Auto-generated method stub
33         Test_16 t1 = new Test_16();
34         t1.setTitle("Test_16");
35         t1.setSize(400,400);
36         t1.setFocusable(true);
37         t1.setLocationRelativeTo(null);
38         t1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
39         t1.setVisible(true);        
40     }    
41     
42     class JP extends JPanel{
43         private int radius = 5;
44         
45         protected void paintComponent(Graphics g){
46             super.paintComponent(g);
47             g.drawOval(x, y, 2*radius, 2*radius);
48         }        
49     }
50     public void actionPerformed(ActionEvent e) {
51         // TODO Auto-generated method stub
52         if(e.getSource() == j1)
53         {        
54             x -= 20;
55             repaint();
56         }
57         else if(e.getSource() == j2){
58             x += 20;
59             repaint();
60         }else if(e.getSource() == j3){
61             y -= 20;
62             repaint();
63         }else if(e.getSource() == j4){
64             y += 20;
65             repaint();
66         }            
67     }    
68 }
Test_16.java
原文地址:https://www.cnblogs.com/wanjiang/p/5635490.html