EDIT: Fixed up code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
public class JumpingBall extends JPanel{
@Override
public Dimension getPreferredSize()
{
return new Dimension(300,300);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D rectangle = (Graphics2D) g;
rectangle.setColor(Color.BLACK);
rectangle.fillRect(0,270,300,30);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Jumping Ball");
frame.getContentPane().add(new JumpingBall());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}
I've set myself the task of writing some code that simple makes a ball jump from the floor at the users command. Step 1 was to create a window and a floor - I noticed that the location I added my floor tended to be off screen and discovered here that frame.setSize(x,y) includes the borders and you should embed a JPanel inside the frame and size that instead. However upon attempting to make these changes my rectangle.fillRect(x,y,width,height) seems to appear as a small square top center regardless of the variables. Why could this be happening?
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
public class JumpingBall extends JPanel{
public void paint(Graphics g){
Graphics2D rectangle = (Graphics2D) g;
rectangle.setColor(Color.BLACK);
rectangle.fillRect(0,0,300,30);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Jumping Ball");
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300,300));
panel.add(new JumpingBall());
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
}