e.getY() return value higher than expected

174 views Asked by At

When I press somewhere near Top-Left of the window, for some reason the output result for e.getY() is higher by about 40 than e.getX(). I don't see why... do you? Something is not clear to me regarding e.getY().

//BBDemo.java - The main program and window creation
import javax.swing.*;


public class BBDemo extends JApplet{        //this isn't Applet !

public int offset=400;
public static void main(String[] args) {
    // TODO Auto-generated method stub

    JFrame win = new JFrame("Bouncing Ball Demo");
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    win.setContentPane(new BBPanel());

    win.pack();
    win.setVisible(true); 
 }
}//endclass BBDemo

//BBPanel.java - The JPanel which organizes the GUI

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/////////////////////////////////////////////////////////////////// BBPanel
public class BBPanel extends JPanel {
BallInBox m_bb;   // The bouncing ball panel ///in order to take the Timer->setAnimation from m_bb
Ball BallN;
//========================================================== constructor
/** Creates a panel with the controls and bouncing ball display. */
BBPanel() {
    //... Create components
    m_bb = new BallInBox();   
    BallN=new Ball(400,400,400);

    JButton startButton = new JButton("Start");        
    JButton stopButton  = new JButton("Stop");

    //... Add Listeners
    startButton.addActionListener(new StartAction());
    stopButton.addActionListener(new StopAction());
    addMouseListener(new PressBall());

    //... Layout inner panel with two buttons horizontally    ///why inner and outer?
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());         ///Flow???
    buttonPanel.add(startButton);
    buttonPanel.add(stopButton);

    //... Layout outer panel with button panel above bouncing ball   ///???
    this.setLayout(new BorderLayout());              ///this ???     ///Board???
    this.add(buttonPanel, BorderLayout.NORTH);       ///this, NORTH, ???
    this.add(m_bb       , BorderLayout.CENTER);      ///this, CENTER, ???
}//end constructor

////////////////////////////////////// inner listener class StartAction
class StartAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        m_bb.setAnimation(true);
    }
}


//////////////////////////////////////// inner listener class StopAction
class StopAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        m_bb.setAnimation(false);
    }
}

public class PressBall implements MouseListener {

    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        //System.out.print(BallN.m_x-BallN.getDiameter()/2+"   ");
        System.out.print(e.getX()+"   ");
        //System.out.print(BallN.m_x+BallN.getDiameter()/2+"             ");
        //System.out.print(BallN.m_y-BallN.getDiameter()/2+"   ");
        System.out.print(e.getY()+"   ");
        //System.out.println(BallN.m_y+BallN.getDiameter()/2+"             ");

        if ((e.getButton() == 1)
                && (e.getX() >= BallN.m_x-BallN.getDiameter()/2 && e.getX() <=     
BallN.m_x+BallN.getDiameter()/2 && e.getY() >=  BallN.m_y-BallN.getDiameter()/2 && e.getY() <=   
BallN.m_y+BallN.getDiameter()/2 ))
                      {     m_bb.setAnimation(false);

                  }else{}
               }
            @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }


    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

  }

}//endclass BBPanel   


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/////////////////////////////////////////////////////////////// BouncingBall
public class BallInBox extends JPanel {
//============================================== fields
public Ball m_ball  = new Ball(400,400,400);    
private int   m_interval  = 40;  // Milliseconds between updates.
private Timer m_timer;           // Timer fires to animate one step.

//=================================================== constructor
public BallInBox() {
setPreferredSize(new Dimension(800, 800));
setBorder(BorderFactory.createLineBorder(Color.BLACK));
m_timer = new Timer(m_interval, new TimerAction());
}

//========================================================= setAnimation    

public void setAnimation(boolean turnOnOff) {
if (turnOnOff) {
    m_timer.start();  // start animation by starting the timer.
} else {
    m_timer.stop();   // stop timer
 }
}


//======================================================= paintComponent
public void paintComponent(Graphics g) {
super.paintComponent(g);  // Paint background, border
m_ball.draw(g);           // Draw the ball.
// m_ball.changeColor(g);
}

class TimerAction implements ActionListener {
//================================================== actionPerformed

public void actionPerformed(ActionEvent e) {
    m_ball.setBounds(getWidth(), getHeight());                ///???
    m_ball.move();  // Move the ball.
    repaint();      // Repaint indirectly calls paintComponent.    ///why "indirectly"?

}

/*  public void mousePressed(MouseEvent e) {
       System.out.println("dfvsd");

     if ((e.getButton() == 1)
            && (e.getX() >= 400- m_ball.m_x && e.getX() <= 400+ m_ball.m_x && e.getY() >= 
400- m_ball.m_x && e.getY() <= 400+ m_ball.m_x)) {m_timer.stop();
          // System.out.println("dfvsd");
          }else{}
    }*/
}
//////////////////////////////////////// inner listener class StopAction


}//endclass


import java.awt.*;
///////////////////////////////////////////////////////////////// BallModel
public class Ball {
//... Constants
final static int DIAMETER = 50;

//... Instance variables
static int m_x;           // x and y coordinates upper left
static int m_y;
/*
private int m_velocityX;   // Pixels to move each time move() is called.
private int m_velocityY;*/

private int m_rightBound;  // Maximum permissible x, y values.
private int m_bottomBound;
public int i=0;
public int offset=400;

//======================================================== constructor
public Ball(int x, int y, int offset) {
    m_x = x;
    m_y = y;
    //offset=400;
}

//======================================================== setBounds
public void setBounds(int width, int height) {
    m_rightBound  = width  - DIAMETER;      
    m_bottomBound = height - DIAMETER;
}

//============================================================== move
public void move() {
    double degrees=(double) i;
    double radians=Math.toRadians(degrees);

    double Sinu=Math.sin(radians);
    double Sinu200=Math.sin(radians)*300;
    int SinuInt=(int) Sinu200;
    m_y=offset+SinuInt;
    //z=offset-SinuInt;
    double Cos=Math.cos(radians);
    double Cos200=Math.cos(radians)*300;
    int CosInt=(int) Cos200;
    m_x=offset+CosInt;
    i++;   // j--;
    if (i==360) i=0;
    //w=offset-CosInt;
    /*
    //... Bounce the ball off the walls if necessary.
    if (m_x < 0) {                  // If at or beyond left side
        m_x         = 0;            // Place against edge and
        m_velocityX = -m_velocityX; // reverse direction.

    } else if (m_x > m_rightBound) { // If at or beyond right side
        m_x         = m_rightBound;    // Place against right edge.
        m_velocityX = -m_velocityX;  // Reverse direction.
    }

    if (m_y < 0) {                 // if we're at top
        m_y       = 0;
        m_velocityY = -m_velocityY;

    } else if (m_y > m_bottomBound) { // if we're at bottom
        m_y       =  m_bottomBound;
        m_velocityY = -m_velocityY;
    }*/
}

//============================================================== draw
public void draw(Graphics g) {
    g.setColor(Color.green);
    g.fillOval(m_x, m_y, DIAMETER, DIAMETER);

}


//======================================================== setPosition
public void setPosition(int x, int y) { 
    m_x = x;
    m_y = y;
 }

}
2

There are 2 answers

0
vandale On BEST ANSWER

If the window is decorated, then you have to take into account the title bar height.

0
peter.petrov On

This is probably due to the blue strip (title bar, not sure if that's the right term) which most GUI programs have at their top.