I'm trying to have a JFrame with a button on it and when i click it the ball appear on the top left. Then, if i click it again the x,y position changes and it moves. The problem is i can't seem to get the ball to appear on the JFrame after i click the button. Only the button appeared.
My source code:
package prac;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Prac extends JComponent {
private int x = 0;
private int y = 0;
private void moveBall() {
x = x + 1;
y = y + 1;
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Sample Frame");
JPanel buttonPanel = new JPanel();
JButton moves = new JButton("Click to move ball");
Prac game = new Prac();
buttonPanel.add(moves);
frame.setSize(500, 500);
frame.add(game);
frame.add(buttonPanel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
moves.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent action) {
game.moveBall();
game.repaint();
}
});
}
}
Thanks
Add this line after creating your
Prac
object.Result: