禁止白嫖!!!
在窗体内使用边界布局添加三个控件JLabel(北)、JPanel(中)、JButton(南),当鼠标在JButton内移动时,JPanel显示随机背景色,JLabel显示鼠标在JButton内的坐标,运行效果如图。(要求提交代码、运行截图和视频)
package main.com.edu.shengda.shangke;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.*;
//鼠标
public class MouseControl extends JFrame implements MouseMotionListener{
private JFrame frame;
private JLabel tf;
Random rd = new Random();
JPanel panel = new JPanel();
JButton butButton = new JButton("移动换色");
Font fnt = new Font("Serief", Font.ITALIC + Font.BOLD, 30);
public static void main(String[] args){
MouseControl two = new MouseControl();
two.go();
}
private void go() {
frame = new JFrame("鼠标按键测试");
//添加一个容器
Container contentPane = frame.getContentPane();
//这两行标签
tf = new JLabel();
contentPane.add(tf, BorderLayout.NORTH);
tf.setFont(fnt); //设置标签中的字体
tf.setForeground(Color.BLUE); //设置标签中的文字颜色
//添加一个按钮
frame.add(butButton,BorderLayout.SOUTH);
//注册监听程序
butButton.addMouseMotionListener(this);
frame.setSize(800 , 800);
frame.setVisible(true);
//添加一个面板
frame.add(panel,BorderLayout.CENTER);
}
@Override
public void mouseDragged(MouseEvent e) {
//按住鼠标拖动才会调用
// TODO Auto-generated method stub
String s = "鼠标拖动的坐标: X =" +e.getX() + " Y =" + e.getY();
tf.setText(s);
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
//设置随机颜色生成在面板
Color color = new Color(rd.nextInt(256),rd.nextInt(256),rd.nextInt(256));
panel.setBackground(color);
String s = "鼠标在按钮移动时的坐标: X =" +e.getX() + " Y =" + e.getY();
tf.setText(s);
}
}