1

What I'm trying to do

Making a Pong game where the Y axis gets the value from my cursor according to the application

What did I tried

private void pallet() {
    ycur=(int)MouseInfo.getPointerInfo().getLocation().getY();
}

This way I get the Y value according to my monitor instead of the application.

I also tried to use the MouseEvent.getY(), but I get the error when trying to call this method from the main.

private void pallet() {
    ycur=(int)MouseInfo.getPointerInfo().getLocation().getY();
}

This is how my code looks like, I think the problem lies in how I'm using my main and methods but I'm not sure.

public class MyFirst extends JPanel {

    public int x = 500, y = 300, border = 30;
    public boolean goingDown = true;
    public int ycur, cursor;


    public void moveBall() {
        x++;
        if (goingDown == true) {
            y++;
        } else if (goingDown == false) {
            y--;
        }

        if (y == getHeight() - border) {
            goingDown = false;
        } else if (y == 0) {
            goingDown = true;
        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x, y, 30, 30);
        g.fillRect(30, ycur, 15, 100);
    }

    public static void main(String[] args) throws InterruptedException     {
        JFrame frame = new JFrame("Pong");
        frame.pack();
        frame.setSize(1000, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        MyFirst game = new MyFirst();
        frame.add(game);
        while (true) {
            game.pallet(e);
            game.moveBall();
            game.repaint();
            Thread.sleep(10);
        }
    }

    public void pallet(MouseEvent e) {
        ycur=e.getY();
    }

}
halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61
creativename
  • 304
  • 2
  • 16

1 Answers1

2

Problems with your code:

  • As already mentioned, you're fighting against Swing's event-driven architecture. Instead of a while true loop, use listeners, including a MouseMotionListener ot track the changes in the mouse location, and an ActionListener tied to a Swing Timer to move the ball.
  • Avoid using Thread.sleep(...) in Swing GUI's except with great care as this can put the entire application to sleep.
  • Avoid putting too much logic within the main method. This method should be short, should create the key objects, connect them, set the program in motion and that's it.
  • Paint with the paintComponent method, not the paint method. It results in smoother animation with its double buffering.

For example:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class MoveBallTest extends JPanel{
    private static final int PREF_W = 1000;
    private static final int PREF_H = 600;
    private static final int TIMER_DELAY = 12;
    private static final int SPRITE_WIDTH = 30;
    private static final Color OVAL_SPRITE_COLOR = Color.RED;
    private static final Color RECT_SPRITE_COLOR = Color.BLUE;
    private static final int DELTAY_Y = 1;
    private boolean goingDown = true;
    private Timer timer = new Timer(TIMER_DELAY, this::timerActionPerformed);
    private int ovalSpriteY;
    private int rectSpriteY;

    public MoveBallTest() {
        timer.start();
        MyMouse myMouse = new MyMouse();
        addMouseMotionListener(myMouse);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(OVAL_SPRITE_COLOR);
        g.fillOval(SPRITE_WIDTH, ovalSpriteY, SPRITE_WIDTH, SPRITE_WIDTH);
        g.setColor(RECT_SPRITE_COLOR);
        g.fillRect(SPRITE_WIDTH, rectSpriteY, SPRITE_WIDTH / 2, SPRITE_WIDTH * 3);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    public void timerActionPerformed(ActionEvent e) {
        if (ovalSpriteY <= 0) {
            goingDown = true;
        } else if (ovalSpriteY >= getHeight() - SPRITE_WIDTH) {
            goingDown = false;
        }

        ovalSpriteY += goingDown ? DELTAY_Y : -DELTAY_Y;
        repaint();
    }

    private class MyMouse extends MouseAdapter {
        @Override
        public void mouseMoved(MouseEvent e) {
            rectSpriteY = e.getY();
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("MoveBallTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MoveBallTest());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373