首页 > 代码库 > 【Java】 用MouseAdapter模拟按钮的实现
【Java】 用MouseAdapter模拟按钮的实现
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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。