我画好了一条线段,存为了Line2D对象,我想问,如何去选中这个对象啊, 就是我鼠标移动到这个线段上面就表示选中了。然后我可以给他一个右键弹出菜单,在线等答复。
------解决方案--------------------
直接示例,可以自己去查看API:
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Line2DGainedDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame();
}
});
}
}
class MainFrame extends JFrame{
private static final long serialVersionUID = -9118470974041744156L;
private Line2D line2D = new Line2D.Double(100, 100, 200, 100);
public MainFrame(){
initialized();
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void initialized() {
JPanel panel;
add(panel = new JPanel(){
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g) {
super.paint(g);
((Graphics2D)g).draw(line2D);
}
});
panel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
System.out.println(e.getPoint());
if(line2D.intersectsLine(new Line2D.Double(e.getPoint(), e.getPoint()))){
JOptionPane.showMessageDialog(MainFrame.this, "你选择了线条");
}
}
});
}
}