标签:
第一个程序:
1 import java.awt.Graphics; 2 import java.awt.event.*; 3 4 import javax.swing.*; 5 6 public class Test_16_8 extends JFrame{ 7 private int x = 0, y = 0; 8 9 public Test_16_8(){ 10 JP jp1 = new JP(); 11 jp1.addMouseListener(new MouseAdapter(){ 12 public void mouseClicked(MouseEvent e){ 13 x = e.getX(); 14 y = e.getY(); 15 repaint(); 16 } 17 }); 18 add(jp1); 19 } 20 public static void main(String[] args) { 21 // TODO Auto-generated method stub 22 Test_16_8 T1 = new Test_16_8(); 23 T1.setTitle("Test_16.8"); 24 T1.setSize(200,200); 25 T1.setLocationRelativeTo(null); 26 T1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 27 T1.setVisible(true); 28 } 29 30 class JP extends JPanel{ 31 protected void paintComponent(Graphics g){ 32 super.paintComponent(g); 33 g.drawString("("+x+","+y+")", getWidth()/2, getHeight()/2); 34 } 35 } 36 }
效果图:
第二个程序:
1 import java.awt.Graphics; 2 import java.awt.event.*; 3 4 import javax.swing.*; 5 6 public class Test_16_8 extends JFrame{ 7 private int x = 0, y = 0; 8 9 public Test_16_8(){ 10 JP jp1 = new JP(); 11 jp1.addMouseListener(new MouseAdapter(){ 12 public void mousePressed(MouseEvent e){ 13 x = e.getX(); 14 y = e.getY(); 15 repaint(); 16 } 17 public void mouseReleased(MouseEvent e){ 18 x = 0; 19 y = 0; 20 repaint(); 21 } 22 }); 23 add(jp1); 24 } 25 public static void main(String[] args) { 26 // TODO Auto-generated method stub 27 Test_16_8 T1 = new Test_16_8(); 28 T1.setTitle("Test_16.8"); 29 T1.setSize(200,200); 30 T1.setLocationRelativeTo(null); 31 T1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 32 T1.setVisible(true); 33 } 34 35 class JP extends JPanel{ 36 protected void paintComponent(Graphics g){ 37 super.paintComponent(g); 38 g.drawString("("+x+","+y+")", getWidth()/2, getHeight()/2); 39 } 40 } 41 }
效果图:
按下: 松开:
标签:
原文地址:http://www.cnblogs.com/wanjiang/p/5637745.html