BiScOtTiNo
BiScOtTiNo

Reputation: 174

MouseListener mouseClicked() missing first event

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);
   }
}

now inner class

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);
    }
}

meanwhile I make first click, my GUI blink, Click Counter print that i have made 1 click, but yet i don't get my first circle. If i keep clicking everything work fine, it prints next circle, increase Counter and draw line between them, so i dont get why first circle is missing

Upvotes: 3

Views: 125

Answers (1)

christian.s
christian.s

Reputation: 447

Look at this:

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

xClick and yClick are not initialized the first time

Upvotes: 2

Related Questions