java通过使用MouseAdapter实现在窗口中用鼠标抓按钮的功能来演示适配器的使用

package ch10;
import java.awt.event.*;
import javax.swing.*;
public class MouseAdapterDemo extends MouseAdapter{
	JFrame f;
	JPanel p;
	JButton b;
	public MouseAdapterDemo() {
		f = new JFrame("抓到按钮有奖");
		p = new JPanel();
		b = new JButton("来抓我啊");
		b.addMouseListener(this);
		p.add(b);
		f.add(p);
		f.setSize(400,300);
		f.setLocation(100,100);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
	}
	//重写鼠标进入的事件处理方法
	public void mouseEntered(MouseEvent e) {
		//产生随机数,作为新坐标
		int x = (int)(Math.random()*380);
		int y = (int)(Math.random()*250);
		b.setLocation(x,y);
	}
	public static void main(String[] args) {
		MouseAdapter m = new MouseAdapterDemo();
	}

}

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java程序现,在窗口中加入一个按、标签和弹出式列表,并用“按现关闭当前窗口的示例代码: ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyFrame extends JFrame { private JLabel label; private JButton button; private JPopupMenu popupMenu; public MyFrame() { super("窗口标题"); // 设置窗口标题 // 创建标签 label = new JLabel("标签文本"); label.setBounds(20, 20, 100, 30); add(label); // 创建按 button = new JButton("关闭窗口"); button.setBounds(20, 60, 100, 30); add(button); // 为按添加点击事件监听器 button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); // 关闭窗口 } }); // 创建弹出式列表 popupMenu = new JPopupMenu(); popupMenu.add(new JMenuItem("列表项1")); popupMenu.add(new JMenuItem("列表项2")); popupMenu.add(new JMenuItem("列表项3")); // 为标签添加鼠标右键事件监听器,显示弹出式列表 label.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); // 设置窗口大小、位置和可见性 setSize(200, 150); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new MyFrame(); } } ``` 运行程序后,会弹出一个窗口,其中包含一个标签、一个按和一个弹出式列表。当点击按时,窗口会关闭;当右键点击标签时,会弹出弹出式列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值