How could my two classes share the same JFrame or Frame? - java

Alright, so my first class creates the Frame and also places a red rectangle in it which I can move. Now what i'm doing is, creating another class for a blue rectangle.
Now in my attempt i have created the second class and also extended the first class unto it; which doesn't seem to do the job.
Summery:
What do I need to do so they share the same frame? Is there a method for this?
SOLVED VERSION
My Code(First Class): EDITED
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, g = 0;
private Color color;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 330) // stops us from going through the ground
{
vely = 0;
y = 330;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_UP) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_LEFT) {
velx = -1;
}
{
if (code == KeyEvent.VK_RIGHT) {
velx = 1;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
public static void main (String arge[]){
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
(Second Class): EDITED
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Incoming extends MyGame {
private Color color;
int x = 0, y = 0, velx = 0, vely = 0;
public Incoming() {
color = Color.BLUE;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 330) // stops us from going through the ground
{
vely = 0;
y = 330;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_S) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_NUMPAD8) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_NUMPAD4) {
vely = 0;
velx = -1;
}
{
if (code == KeyEvent.VK_NUMPAD6) {
vely = 0;
velx = 1;
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
velx = 0;
vely = 0;
}
}
Thank you

You could either take advantage of the color property support of the component or supply your own color property which could set and retrieved through the use of setters and getters
The following example simply uses the components existing foreground property...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GameExample {
public static void main(String[] args) {
new GameExample();
}
public GameExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
MyGame game = new MyGame();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyGame extends JPanel implements ActionListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx = 0, vely = 0, g = 0;
public MyGame() {
t.start();
setFocusTraversalKeysEnabled(false);
setForeground(Color.RED);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right-pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "up-released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "down-released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "left-released");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "right-released");
ActionMap am = getActionMap();
am.put("up-pressed", new YDelatAction(-1));
am.put("down-pressed", new YDelatAction(1));
am.put("left-pressed", new XDelatAction(-1));
am.put("right-pressed", new XDelatAction(1));
am.put("up-released", new YDelatAction(0));
am.put("down-released", new YDelatAction(0));
am.put("left-released", new XDelatAction(0));
am.put("right-released", new XDelatAction(0));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getForeground());
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 330) // stops us from going through the ground
{
vely = 0;
y = 330;
}
x += velx;
y += vely;
repaint();
}
public class XDelatAction extends AbstractAction {
private int value;
public XDelatAction(int value) {
this.value = value;
}
#Override
public void actionPerformed(ActionEvent e) {
vely = 0;
velx = value;
}
}
public class YDelatAction extends AbstractAction {
private int value;
public YDelatAction(int value) {
this.value = value;
}
#Override
public void actionPerformed(ActionEvent e) {
vely = value;
}
}
}
}
This would allow you to create a new instance that use a different color by doing...
MyGame game = new MyGame();
game.setForeground(Color.BLUE);
Or you could create a new subclass using something like...
public class MyBlueGame extends MyGame {
public MyBlueGame () {
setForeground(Color.BLUE);
}
}
Generally speaking, you should favour the key bindings API over KeyListener as it provides more control over the level of focus required to generate key events and generally produces more re-usable and configurable code (IMHO)
Updated
So, based on you example code...
Each class is going to need it's own color property, which independent of the other, otherwise the inheritance is going to get in the way (and the parent will want to use the value of the child)
You will also need to change the keyPressed and keyReleased methods for the child class so that the two rectangles can move independently of each other.
This is not my preferred solution. I would have a single game surface which was capable of rendering the state of the overall game (all the entities) and would provide a means by which the gaming elements could be added (and possibly removed) from the surface and some kind of controller that would be able to control the way in which those elements are updated...but that's just me...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GameTest {
public static void main(String[] args) {
new GameTest();
}
public GameTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx = 0, vely = 0, g = 0;
private Color color;
public MyGame() {
color = Color.RED;
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 330) // stops us from going through the ground
{
vely = 0;
y = 330;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_UP) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_LEFT) {
velx = -1;
}
{
if (code == KeyEvent.VK_RIGHT) {
velx = 1;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
}
public class Incoming extends MyGame {
private Color color;
int x = 0, y = 0, velx = 0, vely = 0;
public Incoming() {
color = Color.BLUE;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 330) // stops us from going through the ground
{
vely = 0;
y = 330;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_NUMPAD2) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_NUMPAD8) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_NUMPAD4) {
vely = 0;
velx = -1;
}
{
if (code == KeyEvent.VK_NUMPAD6) {
vely = 0;
velx = 1;
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
velx = 0;
vely = 0;
}
}
}

i think all what you have to do is to set the colour as a parameter for your class MyGame , to add a field colour to your class.
private Color colour;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Colour);
g.fillRect(x,y,70,40);
}
JFrame f = new JFrame();
MyGame s = new MyGame();
s.setCoulor(Color.RED) // s.setCoulor(Color.BLUE)
f.add(s);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600,400);
f.setVisible(true);

Related

Eclipse vs BlueJ issue

I tried this code in BlueJ which should create a rectangle and move it around but it does not function. Then I put the same exact code into Eclipse and it functions as I thought it would. Any ideas to why this works in Eclipse but not in BlueJ?
import javax.swing.*;
import java.awt.*;
public class Shapes
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Test");
Draw object = new Draw();
frame.add(object);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Draw extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5,this);
int x = 0, y = 0, velX = 0, velY = 0;
public Draw()
{
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x,y,100,20);
}
public void actionPerformed(ActionEvent e)
{
x += velX;
y += velY;
repaint();
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT)
{
velX = -1;
velY = 0;
}
if(c == KeyEvent.VK_UP)
{
velX = 0;
velY = 1;
}
if(c == KeyEvent.VK_RIGHT)
{
velX = 1;
velY = 0;
}
if(c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = -1;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velX = 0;
velY = 0;
}
}
I can see what you mean I believe it attaches it to that corner of the screen because when I resize the screen it moves with that corner. I think its not that BlueJ can't Run it properly i believe it can but it does it differently than what eclipse does.
I believe this question asks the same thing and it gets pretty good answers you should look at it first.

Image circling the window using JApplet

So here's where I am stuck... I got it to go to the end of the window horizontally, then go down, but I don't know how to make it go left after it reaches the bottom of the window and then go up when it reaches the left side of the screen.
Thanks,
import javax.swing.*;
import java.awt.*;
public class AnimatedImageApplet extends JApplet implements Runnable {
private static final long serialVersionUID = 1L;
private Thread t = null;
private Image image;
private int x = 0;
private int y = 0;
private static final int vx = 1;
private static final int vy= 1;
private boolean horizontal = true;
private boolean vertical = true;
public void init() {
image = getImage(getDocumentBase(), "face.png");
}
public void start() {
if (t == null) {
t = new Thread(this);
t.start();
}
}
public void paint(Graphics canvas) {
canvas.fillRect(0,0,getWidth(),getHeight());
synchronized (this) {
canvas.drawImage(image, x, y, this);
}
}
#Override
public void run() {
int direction = 1;
while (true) {
synchronized (this) {
x += vx * direction;
y += vy * (horizontal ? 0 : 1);
if (x + image.getWidth(this) == getWidth()) {
horizontal = false;
direction = 0;
}
}
repaint();
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Conceptually, the idea is simple enough. When you reach one of your edges, you need to change the direction of your movement.
if x + image.width > width then go down
else if x < 0 then go up
else if y + image.height > height then go left
else if y < 0 then go right
for clock wise motion.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MoveTest {
public static void main(String[] args) {
new MoveTest();
}
public MoveTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
private int xDelta = 2;
private int yDelta = 0;
private int x, y = 0;
public TestPane() {
try {
img = ImageIO.read(...);
} catch (IOException ex) {
ex.printStackTrace();
}
Timer timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
x += xDelta;
y += yDelta;
if (x + img.getWidth() > getWidth()) {
x = getWidth() - img.getWidth();
xDelta = 0;
yDelta = 2;
} else if (x < 0) {
x = 0;
xDelta = 0;
yDelta = -2;
}
if (y + img.getHeight() > getHeight()) {
y = getHeight() - img.getHeight();
xDelta = -2;
yDelta = 0;
} else if (y < 0) {
y = 0;
xDelta = 2;
yDelta = 0;
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}
}
You should be careful of threads in Swing as Swing is not thread save. Have a look at Concurrency in Swing and How to use Swing Timers for more details

Somehow my Java animation isn't moving

I'm trying to make a movable object in a Java frame by pressing the arrow keys.
Somehow my animation isn't doing anything, neither is it showing the keyCode (if I would be pressing the wrong keys) through a System.out.println().
Here's my code, I'm hoping someone can look through it, maybe test it out himself and figure out where the problem's located for me? I would be very grateful, cause I'm stuck with this for hours now :(
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GUI extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
public GUI(){
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 30, 30);
}
public void actionPerformed(ActionEvent e){
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT){
velX = -1;
velY = 0;
}
else if(c == KeyEvent.VK_UP){
velX = 0;
velY = -1;
}
else if(c == KeyEvent.VK_RIGHT){
velX = 1;
velY = 0;
}
else if(c == KeyEvent.VK_DOWN){
velX = 0;
velY = 1;
}
else System.out.println(e.getKeyChar() + " = " + c);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args){
GUI t = new GUI();
JFrame jf = new JFrame();
jf.setTitle("Animation");
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}
In your main method, add the JPanel to the JFrame before calling setVisible:
public static void main(String[] args){
GUI t = new GUI();
JFrame jf = new JFrame();
jf.add(t);
jf.setTitle("Animation");
jf.setSize(600,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}

How do I move a graphic across the screen with arrow keys?

I'm trying to create the beginning of a simple game. The first thing I am trying to do is import a graphic into my code and move it across the screen. I was able to draw a ball on the screen and move it around but when I import a graphic from a file I am unable to move it around. What am I missing or doing wrong?
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
double x = 0, y = 0, velX = 0, velY = 0;
private ImageIcon image;
public Game(){
setBackground(Color.WHITE);
t.start();
addKeyListener(this);
this.setFocusable(true);
setFocusTraversalKeysEnabled(false);
image = new ImageIcon ("ship.gif");
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
i.paintIcon(this, g, 0, 0);
}
public void actionPerformed(ActionEvent e){
repaint();
x += velX;
y += velY;
if(x<0){
velX = 0;
x = 0;
}
if(x>750){
velX = 0;
x = 750;
}
if(y<0);{
velY = 0;
y = 0;
}
if(y>550){
velY = 0;
y = 550;
}
}
public void up(){
velY = -1.5;
velX = 0;
}
public void down(){
velY = 1.5;
velX = 0;
}
public void left(){
velX = -1.5;
velY = 0;
}
public void right(){
velX = 1.5;
velY = 0;
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
up();
}
if (code == KeyEvent.VK_DOWN){
down();
}
if (code == KeyEvent.VK_LEFT){
left();
}
if (code == KeyEvent.VK_RIGHT){
right();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
// velX = 0;
// velY = 0;
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
velY = 0;
}
if (code == KeyEvent.VK_DOWN){
velY = 0;
}
if (code == KeyEvent.VK_LEFT){
velX = 0;
}
if (code == KeyEvent.VK_RIGHT){
velX = 0;
}
}
}
My driver is in another class as follows:
import java.awt.Color;
import javax.swing.JFrame;
public class GameDriver {
public static void main(String[] args) {
JFrame f = new JFrame();
Game g = new Game();
f.add(g);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
}
}
Two big problems here:
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
i.paintIcon(this, g, 0, 0);
}
You're reading from a file from within paintComponent(...). Never do this as this will slow your drawing unnecessarily. Read the image once, perhaps in a constructor, and then use the stored image variable in drawing. The paintComponent method should be for painting only, and it should be lean, mean and fast.
You're drawing at 0, 0 always. If you want to move something, draw at a variable position, and then change the values held by the variable and repaint.
Also: You should use Key Bindings to accept key strokes in a Swing application as this will help solve focus issues.
For example, please have a look at my code in this answer.

Java GUI - Moving a circle with no "footprints"

When I run the program and move the circle, it appears as if I'm drawing with a paintbrush in paint. I'm not quite sure what I did to make it to this, or what I can do to make it stop. All help is highly appreciated.
Here is my code:
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JPanel;
import java.awt.event.KeyListener;
public class MovingCar extends JPanel implements ActionListener, KeyListener {
Timer tm = new Timer(5, this);
int x = 0, y = 0, velX = 0, velY = 0;
public MovingCar()
{
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
protected void paintComponent (Graphics g) {
super.paintComponents(g);
g.drawOval(x, y, 50, 50);
}
public void actionPerformed(ActionEvent e){
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if (c == KeyEvent.VK_DOWN) {
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 1;
velY = 0;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
if (x < 0)
{
velX = 0;
x = 0;
}
if (x > 600)
{
velX = 0;
x = 0;
}
repaint();
velY = 0;
velX = 0;
}
public static void main(String[] args) {
MovingCar o = new MovingCar();
JFrame jf = new JFrame();
jf.setTitle("Circle Move");
jf.setSize(600,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(o);
jf.setVisible(true);
}
}
You're calling super.paintComponents(g); instead of super.paintComponent(g);

Categories

Resources