Alright I am beginning to work with GUIs and I was trying to make a simple one person Pong game where your opponent is the wall. There really is no winning per say it is just staying alive.
My problem is trying to make the ball move. I have it so it bounces of the y bounds of the panel, and works great, but I can't seem to make it work using the x bounds as well. (I know there currently is no paddle in my code but that will be added in the future).
This is the JFrame it is extending:
Thanks for any suggestions in advanced!
My problem is trying to make the ball move. I have it so it bounces of the y bounds of the panel, and works great, but I can't seem to make it work using the x bounds as well. (I know there currently is no paddle in my code but that will be added in the future).
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Pong extends FrameWithInheritance {
private int x=0, y=0;
private boolean startPong = false;
private boolean test1 = true;
private boolean test2 = false;
private class MyPanel extends JPanel {
public void paint(Graphics g) {
if(startPong) {
g.setColor(Color.BLUE);
g.drawArc(x, y, 30, 30, 0, 360);
if(y < 160 && test1) {
test2 = false;
x += 20;
y += 20;
}else test2 = true;
if(y > 0 && y <= 160 && test2)
{
test1 = false;
x+=20;
y-=20;
}else test1 = true;
}
}
}
private MyPanel panel;
public Pong(String title) {
super(title);
JMenuBar bar = new JMenuBar();
this.add(bar, BorderLayout.NORTH);
JMenu fileMenu = new JMenu("File");
bar.add(fileMenu);
JMenuItem pongItem = new JMenuItem("Pong");
fileMenu.add(pongItem);
pongItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startPong();
}
});
panel = new MyPanel();
this.add(panel,BorderLayout.CENTER);
while(true) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.repaint();
}
}
public void startPong(){
startPong = ! startPong;
}
public static void main(String[] args) {
new Pong("Pong");
}
}
This is the JFrame it is extending:
Code:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class FrameWithInheritance extends JFrame {
public FrameWithInheritance(String title) {
super(title);
setBounds(200, 200, 505 , 255);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new FrameWithInheritance("Test");
}
}
Thanks for any suggestions in advanced!