Learning the Basics of
Java I'm trying the following exercise:
write a program that starts off showing a ball in the middle of the the screen and 2 buttons: left, right
have the ball move to the left or to the right based on the button pressed.
Make sure the ball does not drop of the screen.
Size of the ball and the delta x are pre determined.
I've written 2 classes:
A class that holds main method and creates a JFrame which adds a JPanel of the type MovingBall to its JFrame
A class MovingBall with 3 methods:
- MovingBall(): contains the creation of the Panel with 2 Buttons
- ActionPerformed(): Determines which button was pressed. Calculates new ballxPos calls repaint ()
- paintComponent (Graphics g): paints the actual ball
in the class I declare the following variables:
private JButton Left, Right;
private int ballxPosition = getWidth()/2;
private final int BALLRADIUS = 50;
private final int STEPSIZE = 13;
All these variables are declared at the beginning of the class outside of any methods. The problem I'm having is with the variable ballxPosition. It returns 0 where I would like to get the actual width of the JPanel.
with some Googling I learned that this is supposed to happen because the Panel hasn't been created yet. But all alternatives given as solution feel all kind of janky.
I did think up of an alternative way and initialize the variable within paintComponent and add a variable the tracks the amount off times I have to offset to left or right. however this feels very janky as well.
What is a clean spot to get the Width of the screen before I kick off any recurring methods (ie: actionPerformed, paintComponent)?
Kind regards,
Newbie Stijn