我需要在通过contains(p)方法移动到矩形的数组列表时更改光标。问题是
我想我可能需要一个线程来改善响应和性能但不确定该方法。提前感谢人们。
public class UnstableCursor extends JPanel{
Rectangle2D rec;
ArrayList<Rectangle2D> recList = new ArrayList<>();
public UnstableCursor(){
}
public static void main(String[] args) {
UnstableCursor uc = new UnstableCursor();
JFrame frame = new JFrame();
Mover mv = new Mover(uc);
uc.addMouseListener(mv);
uc.addMouseMotionListener(mv);
JScrollPane jx = new JScrollPane(uc);
frame.getContentPane().add(jx);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
int x = 5;
for(int i = 0;i < 4;i++){
g2d.setColor(Color.red);
rec = new Rectangle2D.Double(20,x,100,5);
g2d.draw(rec);
recList.add(rec);
x += 50;
}
System.out.println("RecList is: " +recList.size());
}
}
class Mover extends MouseInputAdapter{
UnstableCursor uc;
Rectangle2D rec;
ArrayList<Rectangle2D> reList;
public Mover(UnstableCursor ucc){
uc = ucc;
}
@Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
Point p = e.getPoint();
System.out.println("xxxx");
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
reList = uc.recList;
//System.out.println("List is: "+reList.size());
Iterator <Rectangle2D> recs = reList.iterator();
//--------------------- First Algorithm ----------------------//
if(recs.hasNext()){
rec = recs.next();
if(rec.contains(p)){
System.out.println("inside the rectangle....");
uc.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else{
uc.setCursor(Cursor.getDefaultCursor());
}
}
//--------------------- Second Algorithm ---------------------//
int r = 0;
for(int i = 0;i<(reList.size());i++){
rec = reList.get(r);
//System.out.println("Rect No: "+r+"X: "+rec.getX()+"Y: "+rec.getY());
r++;
if(rec.contains(p)){
System.out.println("inside the rectangle....");
uc.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else{
uc.setCursor(Cursor.getDefaultCursor());
}
}
}
}
答案 0 :(得分:1)
除最后一个矩形外,光标拒绝改变。
您的基本搜索算法错误。找到包含该点的矩形后,您应该设置光标并跳出循环,否则您检查的下一个矩形将不匹配,光标将再次重置。
也...
for(int i = 0;i < 4;i++){
g2d.setColor(Color.red);
rec = new Rectangle2D.Double(20,x,100,5);
g2d.draw(rec);
recList.add(rec);
x += 50;
}
......绘画方法仅适用于绘画。
您不应该创建矩形并将它们添加到数组中,因为当Swing确定需要重新绘制面板时,会不断调用paintComponent()方法。
应该在类的构造函数中将矩形添加到List中,这样每个矩形只会添加一次。