MouseListener mouseClicked()缺少第一个事件

时间:2014-03-12 10:51:59

标签: java swing awt

public  class TesterApplication {
static JPanel CenterPanel;
public static void main(String[] args){
   /* get image MapImg */
   JFrame frame=new JFrame();
   CenterPanel = new JPanel(){
        @Override
        protected void paintComponent(Graphics g){
            g.drawImage(MapImg, 0, 0, null);
        }
   };
   CenterPanel.addMouseListener(new LineBuildListener(new TesterApplication()));
   frame.getContentPane().add(BorderLayout.CENTER, CenterPanel);
   frame.setSize(x, y);
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
   }
}

现在的内部课程

class LineBuildListener implements MouseListener {
     TesterApplication TA;
     int xFirstClick;
     int yFirstClick;
     int ClickCounter=0;
     int xClick;
     int yClick;
     LineBuildListener(TesterApplication TA){
         this.TA=TA;
     }

    @Override
    public void mouseClicked(MouseEvent e) {
        xFirstClick=xClick;
        yFirstClick=yClick;
        xClick=e.getX();
        yClick=e.getY();
        TA.CenterPanel.getGraphics().fillOval(xClick, yClick, 10, 10);
        if(ClickCounter!=0){
            SecondClick();
            ClickCounter++;
        }else{
            ClickCounter++;
        }
        System.out.println(ClickCounter);
    }

    public void SecondClick(){
        TA.CenterPanel.getGraphics().drawLine(xClick, yClick, xFirstClick,yFirstClick);
    }
}

同时我点击第一次,我的GUI闪烁,点击我打了1次点击的计数器打印,但是我没有得到我的第一个圈子。如果我一直点击一切工作正常,它会打印下一个圆圈,增加计数器并在它们之间绘制线条,所以我不明白为什么第一个圆圈缺失

1 个答案:

答案 0 :(得分:2)

看看这个:

 xFirstClick=xClick;
 yFirstClick=yClick;
 xClick=e.getX();
 yClick=e.getY();

第一次没有初始化xClick和yClick