Hello everyone on Daniweb!:)
I'm all new with working with swing and I'm having some problems making my paint method work:/. Atm I'm just tryin to make it write a ball, which I can control into different directions.
Right now there is quite alot of unnecessary stuff in my code but please don't bother about that:P.
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.awt.event.KeyEvent.*;
import java.awt.event.KeyListener.*;
import java.awt.Graphics.*;
public class Boll
{
JFrame frame=new JFrame("hej");
JLabel panel=new JLabel();
private int x=250, y=250;
private boolean ball=true;
private boolean jump=false;
private final int MAXX=500, MAXY=500;
private int left, right, up, down, side;
private Graphics gr;
private int g, m, v, E, p, a, t; //fysikaliska element
public static void main(String[] skit)
{
Boll b=new Boll();
}
public Boll()
{
frame.setVisible(true);
frame.pack();
frame.add(panel);
side=5;
panel.setVisible(true); //sätter ut
panel.setSize(MAXX,MAXY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.addKeyListener(new KeyThing());
panel.paint(gr);
}
public class KeyThing implements KeyListener
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyLocation()==KeyEvent.VK_LEFT)
{
x-=side;
panel.repaint();
}
else if(e.getKeyLocation()==KeyEvent.VK_RIGHT)
{
x+=side;
panel.repaint();
}
else if(e.getKeyLocation()==KeyEvent.VK_UP)
{
y+=side;
panel.repaint();
}
else if(e.getKeyLocation()==KeyEvent.VK_DOWN)
{
y-=side;
panel.repaint();
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
}
public void paint(Graphics g)
{
if (ball==true)
{
g=panel.getGraphics();
g.setColor(Color.green);
g.fillOval(x, y, 30, 30);
g.dispose();
}
}
}
Huge thanks to everyone for taking time to help me!:) I really appreciate it.
//Angelika