所以我有这个任务,但是当鼠标指针位于圆圈内部及其外部时,我还没有显示消息。这是我教科书中的问题。
(几何形状:在圆圈内?)编写一个程序,以半径50绘制以(100,60)为中心的固定圆。无论何时移动鼠标,都会显示一条消息,指示鼠标点是否在圆圈内。鼠标点或其外部,如图15.27a所示
到目前为止,这是我的代码:我没有得到任何“内圈”或“外圈”消息,半径不是50.任何输入都将非常感谢。
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class GeometryInsideACircle extends JFrame {
private CirclePanel canvas = new CirclePanel();
public GeometryInsideACircle() {
JPanel panel = new JPanel();
//JLabel label = new JLabel();
//add(label);
this.add(canvas , BorderLayout.CENTER);
//addMouseListener(this);
//this.add(panel, BorderLayout.SOUTH);
}
public class MouseInfo extends JPanel {
//This is utilized to obtain the circle class because circle would have width = to its height
Ellipse2D.Double circle = new Ellipse2D.Double(100, 60, 50, 50);//circle centered at (100, 60) radius 50
Point p = new Point();//this will get the location of x and y
private boolean isInCircle = false;//set to false until pointer enters the circle
//this constructor will obtain all mouse and circle info utilizing MouseMotionListener and MouseMotionAdapter
public MouseInfo() {
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
if(circle.contains(e.getPoint())) {
isInCircle = true;
}
else {
isInCircle = false;
}
p = e.getPoint();//this should obtain the x and y coordinates based upon mouse activity
repaint();//this will repaint the pointers locations
}
});
}
//this will create/draw a circle
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(circle);
if(isInCircle) {//this should let the user know if mouse pointer is in the circle based upon x and y coordinates
g.drawString("The mouse point is in the circle" + (int)p.getX() +"," + (int)p.getY(), (int)p.getX(), (int)p.getY() );
}
else {//this should let the user know if the mouse pointer is outside of the circle based upon x and y coordinates
g.drawString("The mouse point is outside of the circle" + (int)p.getX() +"," + (int)p.getY(), (int)p.getX(), (int)p.getY() );
}
}
}
public static void main(String[] args) {
GeometryInsideACircle frame = new GeometryInsideACircle();
frame.setTitle("Exercise 16_19");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 350);
frame.setVisible(true);
}
}
答案 0 :(得分:0)
通过简单的改变
public GeometryInsideACircle() {
JPanel panel = new MouseInfo();
add(panel, BorderLayout.CENTER);
}
它像宣传的那样工作。如果你阅读了Ellipse2D.Double的文档,你会发现你说的是高度和高度;不是半径。