1 import java.awt.Frame.*; 2 import java.awt.event.*; 3 import java.awt.*; 4 5 public class Test extends Frame { 6 7 boolean mouseClicked = false; 8 9 public void launchFrame() { 10 this.setLocation(100,100); 11 this.setBackground(Color.GRAY); 12 this.setSize(500, 300); 13 this.addMouseListener(new mouseMonitor()); 14 this.setVisible(true); 15 } 16 17 public void paint(Graphics g) { 18 Color c = g.getColor(); 19 if(mouseClicked == false) { 20 g.setColor(Color.WHITE); 21 g.drawLine(100, 100, 400, 100); 22 g.drawLine(100, 100, 100, 200); 23 g.setColor(Color.BLACK); 24 g.drawLine(100, 200, 400, 200); 25 g.drawLine(400, 100, 400, 200); 26 } 27 else if(mouseClicked == true) { 28 g.setColor(Color.BLACK); 29 g.drawLine(100, 100, 400, 100); 30 g.drawLine(100, 100, 100, 200); 31 g.setColor(Color.WHITE); 32 g.drawLine(100, 200, 400, 200); 33 g.drawLine(400, 100, 400, 200); 34 } 35 g.setColor(c); 36 } 37 38 public class mouseMonitor extends MouseAdapter { 39 public void mousePressed(MouseEvent e) { 40 if(e.getX()<400 && e.getX()>100 && e.getY()<200 && e.getY()>100) { //getX()和getY()是MouseEvent的方法 41 mouseClicked = true; 42 repaint(); // 这里一定记得repaint() 43 } 44 } 45 public void mouseReleased(MouseEvent e) { 46 mouseClicked = false; 47 repaint(); 48 } 49 50 } 51 52 public static void main(String[] args) { 53 Test t = new Test(); 54 t.launchFrame(); 55 } 56 }
【Java】 用MouseAdapter模拟按钮的实现
时间: 2024-10-08 12:06:51