still doesn’t work :clue:
codes :
the panel :
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Screen extends JPanel implements Runnable {
Thread thread = new Thread(this);
public static Ball ball;
public static Player player;
public static Control control;
public static boolean isFirst = true;
public static int screenWidth,screenHeight,screenX,screenY;
public Screen() {
thread.start();
this.addKeyListener(control);
this.setFocusable(true);
}
public void define() {
control = new Control();
ball = new Ball(ball.x, ball.y, ball.height, ball.width);
player = new Player(player.x,player.y,player.width,player.height,player.speed);
screenWidth = this.getWidth();
screenHeight=this.getHeight();
}
public void paintComponent(Graphics g) {
if (isFirst) {
define();
}
g.setColor(new Color(0, 0, 0));
g.fillRect(screenX, 0, screenWidth, screenHeight);
g.setColor(new Color(250, 50, 0));
ball.move(ball.x, ball.y);
ball.draw(g);
g.setColor(new Color(255,255,255));
player.draw(g);
}
public void run() {
// while is true
while (true) {
// do stuff
if (!isFirst) {
}
repaint();
try {
// make the thread slee every 1 milliSecond
// the try and catch are auto-generated
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
the Key class
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Control implements KeyListener{
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==e.VK_RIGHT){
System.out.println("Right");
}else if(e.getKeyCode()==e.VK_LEFT){
System.out.println("LEFT");
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode()==e.VK_RIGHT){
System.out.println("Right");
}else if(e.getKeyCode()==e.VK_LEFT){
System.out.println("LEFT");
}
}
}
the frame class
import java.awt.Dimension;
import javax.swing.JFrame;
public class Frame extends JFrame {
public static Dimension size = new Dimension(800,600);
public static String title ="Pong2.0";
public Frame(){
this.setSize(size);
this.setTitle(title);
//this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
}
public void init(){
Screen screen = new Screen();
this.add(screen);
this.setVisible(true);
}
public static void main(String args[]){
Frame frame = new Frame();
}
}