我有一个程序允许用户在JPanel中释放绘制形状,绘制的形状存储在一般类型的数组列表中(类形状类型扩展的类)。但是,我需要允许用户与形状进行交互。阅读:事件处理程序。知道如何工作吗?
我绘制形状的当前代码,虽然它不相关:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
private ArrayList <shape> shapes;
public enum ShapeType{LINE,OVAL};
public ShapeType shapeType;
public shape currentShape;
public Color currentColor=Color.BLACK;
public DrawPanel(){
shapes= new ArrayList<shape>();
currentShape=null;
setBackground(Color.WHITE);
MouseHandler mouseHandler = new MouseHandler();
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i=0;i<shapes.size();i++)
{
shapes.get(i).draw(g);
}
if(currentShape!=null)
{
currentShape.draw(g);
}
}
public void clearDraw(){
shapes.clear();
repaint();
}
public void setToOval(){
setShapeType(ShapeType.OVAL);
}
public void setToLine(){
setShapeType(ShapeType.LINE);
}
public void setShapeType(ShapeType shape){
shapeType=shape;
}
private class MouseHandler extends MouseAdapter implements MouseMotionListener{
public void mousePressed(MouseEvent event){
if(shapeType!=null){
switch(shapeType){
case LINE:
currentShape = new line(event.getX(),event.getX(),event.getY(),event.getY(),currentColor);
break;
case OVAL:{
currentShape=new oval(event.getX(),event.getX(),event.getY(),event.getY(),currentColor);
}
break;
}
}
}
public void mouseReleased(MouseEvent event){
if(currentShape!=null)
{
currentShape.setMyColor(currentColor);
currentShape.setX2(event.getX());
currentShape.setY2(event.getY());
shapes.add(currentShape);
currentShape=null;
validate();
repaint();
}
}
public void mouseDragged(MouseEvent event){
if(currentShape!=null)
{
currentShape.setMyColor(currentColor);
currentShape.setX2(event.getX());
currentShape.setY2(event.getY());
validate();
repaint();
}
}
}
public void setCurrentColor(Color color){
this.currentColor=color;
}
}
答案 0 :(得分:1)
形状是您在表面上绘制的元素。您无法直接处理它们上的事件。一个选项是处理JPanel中的鼠标事件,并遍历绘制的形状列表。您可以检查一个形状是否位于当前鼠标位置,并根据该结果将currentShape变量设置为此形状(或将currentShape设置为NULL并考虑可能在其他处理程序中选择了NO形状......)< / p>