javaGUI中 随机生成一组位置不同的按钮 并对JButton的左键、右键、双击的监听
2016-03-31 19:44
741 查看
public static int[][] getRandomLocation(int paneWidth,int panelHeight,int n,int blcokWidth,int blockHeight){ int[][] location=new int[n][3]; //x,y,c int i=0; while(i<n){ int x=(int)(Math.random()*paneWidth); //x坐标 int y=(int)(Math.random()*panelHeight); //y坐标 int c=(int)(Math.random()*3); //颜色 boolean keep=false; for(int k=0;k<location.length;k++){ //生成的位置与之前的位置不重叠 if((Math.abs(location[k][0]-x)>blcokWidth*1.5) &&(Math.abs(location[k][1]-y)>blockHeight*1.5)){ keep=true; } } if(keep){ location[i][0]=x; location[i][1]=y; location[i][2]=c; i++; } } return location; }
上面代码为了随机生成一组坐标值
public void addImgBlock(JPanel p,int n){int[][] location=toolUtil.getRandomLocation(p.getWidth(),p.getHeight(),60,50,n);//获取坐标for(int i=0;i<n;i++) {JButton btnBlock = new JButton();blocks.add(btnBlock);btnBlock.addMouseListener(new MyMouseListener());btnBlock.setBounds(location[i][0], location[i][1],60,50);if(location[i][2]==0){btnBlock.setBackground(Color.BLUE);}else if(location[i][2]==1){btnBlock.setBackground(Color.ORANGE);}else{btnBlock.setBackground(Color.GREEN);}imgPane.add(btnBlock);}SwingUtilities.updateComponentTreeUI(this);}
上面代码是根据生成的坐标值随机生成一组按钮 并未它们添加监听事件
class MyMouseListener extends MouseAdapter {public boolean clickFlag;//记录是否已经执行过鼠标双击事件public int clickNum = 0; //判断是否执行双击事件public void mouseClicked(MouseEvent e) {final MouseEvent mouse=e;this.clickFlag = false;if (e.getButton() == e.BUTTON1) { //鼠标左键if (clickNum == 1) {//如果鼠标在规定的时间内已经被单击过一次,则说明这次是双击了,执行双击事件JButton bn = ((JButton) e.getSource());if(bn.getBackground()==Color.GREEN){bn.setVisible(false);removeBtnFromVector(bn);}clickFlag = true;clickNum = 0;return;}java.util.Timer timer = new java.util.Timer();//定义一个定时器timer.schedule(new java.util.TimerTask() {int n = 0;//记录定时器执行的次数@Overridepublic void run() {if (clickFlag) {//如果双击事件已经执行完毕,取消单击事件clickNum = 0;n = 0;this.cancel();return;}if (n == 1) {//如果规定的时间内未执行鼠标双击事件则执行鼠标单击事件JButton bn = ((JButton) mouse.getSource());if(bn.getBackground()==Color.BLUE) {bn.setVisible(false);removeBtnFromVector(bn);}clickFlag = true;clickNum = 0;n = 0;this.cancel();return;}n++;clickNum++;}}, new java.util.Date(), 200);}else if(e.getButton()==e.BUTTON3){JButton bn = ((JButton) e.getSource());if(bn.getBackground()==Color.ORANGE) {bn.setVisible(false);}}}}这段代码的功能是:蓝色按钮左键单击消失 橙色按钮右键单击消失 绿色按钮左键双击消失
相关文章推荐
- IOS开发之UIView总结
- easyui 点击文字展开和收缩节点
- ABP源码分析十八:UI Inputs
- Why I can’t convert my Windows Server 2012 R2 Core to GUI
- UIBezierPath - 贝塞尔曲线
- Ubuntu15.10安装Arduino IDE记录
- android自定义UI组件
- UITableViewController和XML解析还有地图的简单结合
- easyui tree 增加参数
- #调整随机森林的参数(调整n_estimators随机森林中树的数量默认10个树,精度递增显著,但并不是越多越好),加上verbose=True,显示进程使用信息
- miniGUI3.0.12移植到Hi3531
- miniGUI3.0.12移植到Hi3531
- miniUI tree 过滤(filter)的问题
- UI - Cocoa Touch框架
- SPOJ GSS1 Can you answer these queries I(区间合并)
- hdoj 3157 Crazy Circuits 【有下界最小流】
- 整体二分 hdu5412 CRB and Queries
- Mosquitto pub/sub服务实现代码浅析-主体框架
- 开源mqtt代理:mosquitto
- UI控件--Toast