package packaget;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test extends JPanel implements Runnable, KeyListener {
private boolean left, right;
private static double spielerX;
public static void main(String[] args){
//Frame erstellen
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Ball");
frame.setBounds(100,100,500,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Objekt vom Typ Ball (erbt von JPanel + implementiert Runnable)
Test ball = new Test();
frame.add(ball);
//Thread erstellen + starten
new Thread(ball).start();
spielerX = frame.getWidth()*0.5-100*0.5;
}
public Test(){
addKeyListener(this);
}
//Zeichnen des Balls + Rechtecks
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.GREEN);
g.fillRect((int) spielerX, (int) (getHeight()-22), 100, 20);
}
//hoch und runter zwischen dem Frame
public void run() {
while(true){
try{
if(left){
spielerX -= 5;
}
else
if(right){
spielerX += 5;
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Error: " +e, "Fehler!", JOptionPane.ERROR_MESSAGE);
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
right = true;
left = false;
}
}
public void keyReleased(KeyEvent e) {
left = false;
right = false;
}
public void keyTyped(KeyEvent e) {
}
}