我是学习Java的新手,几天来我一直在寻找一种方法来单击绘制的对象,以将鼠标包含在诸如g.drawRect(x,x,x,x)之类的对象中......
我遇到了下面的代码,我试图让它工作,这样我就可以了解在对象中包含鼠标需要什么,但我似乎无法让它工作。
从“有什么方法可以将 MouseListener 添加到 Graphic 对象吗? ”
我试图根据他们给出的提示让它工作,但没有希望:(。
任何帮助表示赞赏。
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class Gui3 extends JFrame {
JFrame frame = new JFrame();
MyDrawPanel drawpanel = new MyDrawPanel();
public static void main(String[] args) {
Gui3 gui = new Gui3();
gui.go();
}
public void go() {
frame.getContentPane().add(drawpanel);
// frame.addMouseListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
class MyDrawPanel extends JComponent implements MouseListener {
Ellipse2D oval = new Ellipse2D.Double(70, 70, 100, 100);
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(70, 70, 100, 100);
}
@
Override
public void mouseClicked(MouseEvent e) {
if ((e.getButton() == 1) && oval.contains(e.getX(), e.getY())) {
repaint();
JOptionPane.showMessageDialog(null, e.getX() + "\n" + e.getY());
}
}
@
Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@
Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@
Override
public void mousePressed(MouseEvent e) {
}
@
Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public boolean contains(int x, int y) {
return oval.contains(x, y);
}
}