For some reason the ball is still going off the top of the frame. Im not sure why.
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; public class Frame extends JFrame { int ovalSpeed = 5; int xCoord = 50; int yCoord = 50; private final int ovalWidth = 25; private final int ovalHeight = 25; private final int WIDTH = 800; private final int HEIGHT = WIDTH / 5 * 4; private Dimension borderlessSize; private Image dbImage; private Graphics dbG; private Dimension d = new Dimension(WIDTH, HEIGHT); //Constructor for the class, and makes the frame. Frame() { addKeyListener(new AL()); setTitle("Frame"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(d); setResizable(false); setVisible(true); setBackground(Color.WHITE); borderlessSize = this.getContentPane().getSize(); System.out.println(borderlessSize.getWidth() + " " + borderlessSize.getHeight()); } //Draws graphics on the screen. public void paint(Graphics g) { dbImage = createImage(getWidth(), getHeight()); dbG = dbImage.getGraphics(); paintComponent(dbG); g.drawImage(dbImage, 0, 0, this); } public void paintComponent(Graphics g) { g.fillOval(xCoord, yCoord, ovalWidth, ovalHeight); repaint(); } public class AL extends KeyAdapter { public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); //If left arrow is pressed. if(keyCode == e.VK_LEFT) { //Tests they're past the left hand portion of the screen, of so, then set its xCoord to 0. if(xCoord <= 0) { xCoord = 0; } //Moves the ball ovalSpeed pixels to the left. else { xCoord += -ovalSpeed; } } //If right arrow is pressed. if(keyCode == e.VK_RIGHT) { //Tests they're past the right hand portion of the screen, of so, then set its xCoord to the width of the frame - the width of the oval. if(xCoord >= borderlessSize.getWidth() - ovalWidth) { xCoord = (int) (borderlessSize.getWidth() - ovalWidth); } //Moves the ball ovalSpeed pixels to the right. else { xCoord += ovalSpeed; } } //If up arrow is pressed. if(keyCode == e.VK_UP) { //Tests they're higher then the upper hand portion of the screen, of so, then set its yCoord to 0. if(yCoord <= 0) { System.out.println(yCoord); System.out.println("top collision"); yCoord = 0; } //Moves the ball ovalSpeed pixels up. else { System.out.println(yCoord); yCoord += -ovalSpeed; } } //If down arrow is pressed. if(keyCode == e.VK_DOWN) { //Tests they're lower the lower hand portion of the screen, of so, then set its yCoord to the height of the frame - the height of the oval. if(yCoord >= borderlessSize.getHeight() - ovalHeight) { yCoord = (int) (borderlessSize.getHeight() - ovalHeight); } //Moves the ball ovalSpeed pixels down. else { yCoord += ovalSpeed; } } } } }