您的位置:首页 > 产品设计 > UI/UE

javaGUI中 随机生成一组位置不同的按钮 并对JButton的左键、右键、双击的监听

2016-03-31 19:44 676 查看
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);}}}}这段代码的功能是:蓝色按钮左键单击消失  橙色按钮右键单击消失  绿色按钮左键双击消失
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: