Java如何实现单击一次鼠标,就在鼠标位置出现一个圆7
发布网友
发布时间:2023-09-29 16:58
我来回答
共4个回答
热心网友
时间:2024-04-06 04:12
用JFrame做;
实现重绘repaint方法;
drawCircle方法即可。
例如如下例子:
public class Draw extends JFrame {
private int x, y;
boolean isVisible = false;
public Draw () {
addHandler();
setSize(500, 500);
setLocation(350, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Draw ();
}
private void addHandler() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
x = e.getX();
y = e.getY();
isVisible = true;
repaint();
} else if (e.getButton() == MouseEvent.BUTTON3) {
isVisible = false;
repaint();
}
}
});
}
public void paint(Graphics g) {
super.paint(g);
if(isVisible){
g.setColor(Color.red);
g.drawOval(x, y, 100, 100);
}
}
}
热心网友
时间:2024-04-06 04:13
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class TEST5 extends JFrame {
// x,y坐标
private int x, y;
//控制显示
boolean isVisible = false;
public TEST5() {
addHandler();
setSize(500, 500);
setLocation(350, 150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TEST5();
}
private void addHandler() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 左键
if (e.getButton() == MouseEvent.BUTTON1) {
x = e.getX();
y = e.getY();
isVisible = true;
repaint();
} else if (e.getButton() == MouseEvent.BUTTON3) {// 右键
isVisible = false;
repaint();
}
}
});
}
public void paint(Graphics g) {
super.paint(g);
if(isVisible){
g.setColor(Color.red);
g.drawOval(x, y, 100, 100);
}
}
}
热心网友
时间:2024-04-06 04:10
捕捉鼠标位置,当点击事件触发时,draw一个圆
热心网友
时间:2024-04-06 04:15
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class TestPoint {
public static void main(String[] args) {
new MyFrame().launch();
}
}
class MyFrame extends Frame {
ArrayList<Point> c = null;
public void launch() {
c = new ArrayList<Point>();
addMouseListener(new Monitor());
setBounds(300,300,400,400);
setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void addPoint(Point p) {
c.add(p);
}
public void paint(Graphics g) {
Iterator<Point> i = c.iterator();
while(i.hasNext()) {
Point p = i.next();
g.fillOval(p.x, p.y, 10, 10);
}
}
private class Monitor extends MouseAdapter {
public void mousePressed(MouseEvent e) {
Point p = new Point(e.getX(), e.getY());
MyFrame f = (MyFrame)e.getSource();
f.addPoint(p);
f.repaint();
}
}
}