Java Paint and JButton

1.2k views Asked by At

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

2

There are 2 answers

0
almightyGOSU On BEST ANSWER

Add this line after creating your Prac object.

Prac game = new Prac();
game.setSize(500, 500);

Result:

Result

0
Roberto Attias On

You should override paint component rather than paint ().

Also, you should add component to the content pane of a Jframe rather than the JFRAME itself.

Most likely your component does not have a proper size. I would suggest:

  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);
     Container c = frame.getContentPane ();
    c.setLayout (new BorderLayout ());
    c.add(game, BorderLayout.CENTER);
    c.add(buttonPanel, BorderLayout.NORTH);

This will cause your game component to expand on most of the frame.