本文主要是介绍点击鼠标,显示鼠标的坐标,以及点击鼠标显示坐标,松开鼠标不显示坐标,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
鼠标事件驱动包含7种事件和两种监听器
对于鼠标事件有7种鼠标事件:
1、鼠标按下后使用 mousePressed
2、鼠标释放后使用 mouseReleased
3、鼠标被点击后使用 mouseClicked
4、鼠标离开源组件后使用 mouseExited
5、鼠标进入源组件后使用 mouseEntered
6、按住鼠标并移动时调用 mouseDragged
7、松开鼠标进行移动时调用 mouseMoved
两种监听器:
1、mouseListener 监听鼠标的按下、释放、点击、移入、移出
2、mouseMotionListener监听鼠标的拖动和移动等行为
这两个小程序是鼠标的点击和释放因此用到的都是mouseListener及其对应的适配器mouseAdapted
package fourteen;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise14_4 extends JFrame{
int x = 20;
int y = 20;
public Exercise14_4(){
coorPanel p = new coorPanel();
add(p);
}
public static void main(String[] args) {
Exercise14_4 frame = new Exercise14_4();
frame.setTitle("Exercise14_4");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class coorPanel extends JPanel{
coorPanel(){
addMouseListener(new MouseAdapter() {//监听器 +适配器
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("(" + x + "," + y +")", x, y);
}
}
}
鼠标点击显示坐标,释放时不显示坐标,简单的采用一个if语句就可以解决问题
package fourteen;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise14_4_2 extends JFrame{
int x = 20;
int y = 20;
int z = 1;
public Exercise14_4_2(){
coorPanel p = new coorPanel();
add(p);
}
public static void main(String[] args) {
Exercise14_4_2 frame = new Exercise14_4_2();
frame.setTitle("Exercise14_4");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class coorPanel extends JPanel{
coorPanel(){
addMouseListener(new MouseAdapter() {//监听器 +适配器
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
z=0;
}
public void mouseReleased(MouseEvent e) {
x = e.getX();
y = e.getY();
z=1;
repaint();
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(z==0)
g.drawString("(" + x + "," + y +")", x, y);
else
System.out.println("asd");
g.drawString(" ", x, y);
}
}
}
这篇关于点击鼠标,显示鼠标的坐标,以及点击鼠标显示坐标,松开鼠标不显示坐标的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!