I had glitching in speech marks because I am farily sure it is not a glitch.
I have just recently started to code using JFrames, in fact I started Java at school couple months ago, but recently I have tried to push my understanding using these handy frames.
I made a program which would bounce a ball around the frame, and I wanted to make it so there would be 2 (for now they would not collide) however whenever I try to add another it simply shows one. Here is the code:
public static void main(String[] args) throws InterruptedException{
JFrame frame = new JFrame("Hello There");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setLayout(new FlowLayout());
Main ball = new Main();
Main ball2 = new Main();
ball2.SetValues(200, 200, Color.BLUE);
frame.add(ball2);
frame.add(ball);
while (true) {
ball.move();
ball.repaint();
ball2.move();
ball2.repaint();
Thread.sleep(5);
}
}
public void move() {
x = x + xDirection;
y = y + yDirection;
if (x < 0) { //If Ball has gone off the screen on x direction
xDirection = 1; //Start moving to the right
} else if (x > getWidth() - 50) { //If x has gone off the screen to the right
xDirection = -1;//Start moving to the left
}
if (y < 0) { //If Ball has gone off the screen on x direction
yDirection = 1; //Start moving to the right
} else if (y > getHeight() - 50) { //If x has gone off the screen to the right
yDirection = -1;//Start moving to the left
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(color);
g.fillOval(x, y, 50, 50);
}
I recently added the line "frame.setLayout(new FlowLayout()" and it appears to show the 2 balls but they are in a glitched state.
Could anyone help me out?