栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java导论】Lab:制作一个用鼠标驱赶文本的GUI界面

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java导论】Lab:制作一个用鼠标驱赶文本的GUI界面

记录完成的课时任务

文章目录
  • Lab题目要求
  • 一、大致思路
  • 二、代码实现
    • 1.引入库
    • 2.具体操作

Lab题目要求

       制作如图所示的GUI界面,要求:文字 “Click me” 随机出现在某一按钮上,当鼠标移动至该按钮时(还未点击)文字自动转移至其他按钮上,这样你的鼠标永远点不中他;所有代码存至一个.java文件中,命名为CatchButtonGameV2.java,在电脑终端 command line 执行时写入命令 java CatchButtonGameV2 9,即可产生该3*3按钮界面(即输入任意完全平方数,作为参数,意为需要设置的按钮数量,然后所有按钮正正方方地表现于界面上,行数 = 列数)。


一、大致思路

       可直接使用JFrame和JButton新建界面框架和按钮,再组合起来;为JButton对象设置监听MouseListener,当鼠标移动至有文本的按钮时,找到该按钮,清除已有文本,并随机找到其他某一按钮,设置文本。

       可以将所有按钮设置于同一数组,通过产生随机数,寻找其他按钮的数组索引,界面初始化时也可用此方法随机赋予某一按钮 “Click me”。

二、具体代码实现 1.引入库

代码如下(注意:如果直接在终端cmd运行程序,可能需要去掉代码中所有非英文字符,包括注释里的):

import javax.swing.*;           // JFrame, JButton(需要用到的组件)
import java.awt.event.*;        // MouseListener, MouseAdapter, MouseEvent
import java.awt.*;              // GridLayout
import java.lang.*;             // Number: Integer
2.具体操作

代码如下(示例):

public class CatchButtonGameV2 extends JFrame {
    int cnt;                 
    JButton buttons[];        // create JButton
    
    
    // 在此构造方法中,所有GUI功能就将基本实现:
    public CatchButtonGameV2(String title, int cnt) {
        // 设置基础参数:标题、大小、关闭方式、布局方式...           
        this.setTitle(title);
        this.setSize(600, 600);
        this.setDefaultCloseOperation(super.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(new GridLayout(cnt, cnt));
        this.cnt = cnt;
        
        this.buttons = new JButton[cnt*cnt];        // create & design JButton
        for (int i = 0; i < cnt*cnt; i++) {    
            buttons[i] = new JButton();                            // make instance
            // 通过循环,将每个按钮实例化,并为每个按钮添加监听鼠标动作的监听器
            buttons[i].addMouseListener(new MouseAdapter() {
                // 虽然想添加的是MouseListener, 但该接口中定义了很多函数,而我们只需要其中一个,而使用接口需要实例化所有定义的函数,
                // 为使代码更简单,我们实际添加的是MouseAdapter,这是一个implement了MouseListener的类,只不过所有都是空的(e.g. public mouseEntered() {})
                // 现在我们可以选择性调用方法了,里面的内容由我们来填充
                public void mouseEntered(MouseEvent e) {
                    // mouseEntered 是MouseListener中的一个方法,鼠标在放置于相应按钮上时即可触发此方法(注意是放置,不需要点击,不同于mouseClicked())
                    JButton thisButton = (JButton)e.getSource();   // thisButton is the button had "Click me" now
                    // 方法getSource()可以返回鼠标事件e作用的对象,由于返回的是Object型,所以需要加(JButton)强制转换
                    // 这里只是新建了一个变量thisButton,便于此方法内调用,对象仍然是原来的对象
                    if(thisButton.getText().equals("Click me")){        
                        thisButton.setText(""); int rand = 0;
                        do {        // do-while循环确保找到可用的按钮才进入下一步
                            rand = (int)(Math.random()*(cnt*cnt));
                            // 注意此处最外围的两个()()必须要有,否则无法正常生成随机数
                            // Math.random()方法可产生0~1的小数,乘上按钮的数量再取整,正好就是数组所有可能的索引值
                        }
                        while(buttons[rand] == thisButton);    // 确保按钮没有找重复————这的确是另外一个按钮 make sure another button has been found to have "Click me"
                        buttons[rand].setText("Click me");
                    }
                }    
            });            
            
            this.getContentPane().add(buttons[i]);                // add all JButton into the JFrame    
        }
    }
    
    

    // 主函部分:
    public static void main(String args[]) {
		int number = 0;
		try {													// check input
			number = (int)Math.sqrt(Integer.parseInt(args[0]));		// get number of rows and columns
            // 将输入的数字开方得到行数(列数);放在try中以监视输入的数字不是完全平方数或不是数字,接着触发catch{}中的操作
		}
		catch(NumberFormatException nfe) {
			System.out.println("Wrong input! It must be an integer which can be sqrted.");
			System.exit(0);
		}
		CatchButtonGameV2 cbg = new CatchButtonGameV2("Catch me if you can!", number);
		
		int rand = (int)(Math.random()*cbg.cnt*cbg.cnt);		// set "Click me" randomly at the very beginning
		cbg.buttons[rand].setText("Click me");
		//cbg.pack();
		cbg.setVisible(true);    // 别忘了设置框架为可见
	} 
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号