Adding an image to a null layout jpanel - java

I am looking to add a JPEG image of Pacman to a null layout JPanel so that I can use a key listener to move the image. Here's the code I have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
public class PacmanCharacterMovement2{
static BufferedImage pacman;
static int xCoor;
static int yCoor;
public static class PacmanPanel extends JPanel implements KeyListener {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(pacman, xCoor, yCoor, null);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
xCoor = xCoor--;
yCoor = yCoor;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
xCoor = xCoor++;
yCoor = yCoor;
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
xCoor = xCoor;
yCoor = yCoor--;
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
xCoor = xCoor;
yCoor = yCoor++;
}
else{}
repaint();
}
public void keyReleased(KeyEvent e) {
}
}
public static void main(String[] agrs){
try {
pacman = ImageIO.read(new File("PacmanCharacter2.jpg"));
} catch (IOException e) {}
xCoor = 30;
yCoor = 30;
JFrame window = new JFrame ("Pacman Movement");
JPanel pacmanPanel = new JPanel ();
pacmanPanel.setLayout(null);
PacmanPanel mainPanel = new PacmanPanel();
window.setContentPane(mainPanel);
window.setSize(600,450);
window.setLocation(350,150);
window.setVisible(true);
}
}
The image appears on the screen but it does not move.

you need to use key blind instead awt keyevents because awt keyevent required focus to listen to event .and also xCoor = xCoor--; not work like u expected you should use xCoor--; or xCoor = xCoor-1; .
this is example for up key you can write for all arrow keys ...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
public class PacmanCharacterMovement2 {
static BufferedImage pacman;
static int xCoor=30;
static int yCoor;
public static class PacmanPanel extends JPanel {
public PacmanPanel() {
this.getInputMap().put(KeyStroke.getKeyStroke("UP"), "doup");
this.getActionMap().put("doup", new AbstractAction("doup") {
public void actionPerformed(ActionEvent evt) {
xCoor--;
yCoor = yCoor;
repaint();
}
}
);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(pacman, xCoor, yCoor, null);
}
}
public static void main(String[] agrs) {
try {
pacman = ImageIO.read(new File("PacmanCharacter2.jpg"));
} catch (IOException e) {
}
xCoor = 30;
yCoor = 30;
JFrame window = new JFrame("Pacman Movement");
PacmanPanel mainPanel = new PacmanPanel();
window.setContentPane(mainPanel);
window.setSize(600, 450);
window.setLocation(350, 150);
window.setVisible(true);
}
}

Key events are only dispatched to the component with focus. A JPanel is not focusable by default so it will never receive key events.
The better approach is to use KeyBinding which can respond to events even when they don't have focus. See Motion Using the Keyboard for more information and working examples.

Related

a JNI error has occurred, please check your installation and try again and A java exception has ocurred error after exporting the program in eclipse

After exporting the program, when I try to run the JAR file, the error occurs:
a JNI error occurred, check your installation and try again followed by a java exception occurred.
I have no idea how to solve this, I don't know if it's something about the code or the Java version
I'll post the code here (the main code) so please help!
My java is: 8 281 as JDK
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
public static int WIDTH = 160;
public static int HEIGHT = 120;
public static int SCALE = 3;
public BufferedImage layer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
public static Enemy enemy;
public static Player player;
public static Ball ball;
public Game() {
this.setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
this.addKeyListener(this);
player = new Player(60, HEIGHT-5);
enemy = new Enemy(60, 0);
ball = new Ball(60, HEIGHT/2 - 1);
}
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame("Pong by Skubs");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new Thread(game).start();
}
public void tick() {
player.tick();
enemy.tick();
ball.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = layer.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0 , WIDTH, HEIGHT);
g.setColor(Color.white);
g.fillRect(0, 60 , WIDTH, HEIGHT/120);
player.render(g);
enemy.render(g);
ball.render(g);
g = bs.getDrawGraphics();
g.drawImage(layer, 0, 0, WIDTH*SCALE, HEIGHT*SCALE, null);
bs.show();
}
#Override
public void run() {
requestFocus();
while(true) {
tick();
render();
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.right = true;
}else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
player.left = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
player.right = false;
}else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
player.left = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
enter code here

How to make smooth animations in java swing

Hi I'm using the Timer class and the repaint method for the JPanel, but whenever I hit DOWN and the space ship moves halfway down the screen, it shrinks and stays in place. It never reaches the bottom of the window. It is the same when I move it to the RIGHT.
Also when I try to place it in a differnt y position, the background isn't black anymore. Can someone help me with this please? Here is a sample of my code:
package javapaint;
import java.awt.Color;
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 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;
public class SpaceShipFlight
{
private JFrame windowFrame;
private BufferedImage shipSprite;
private BufferedImage spaceBackground;
/** MAIN METHOD **/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
SpaceShipFlight window = new SpaceShipFlight();
window.windowFrame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/** CONSTRUCTOR **/
public SpaceShipFlight() throws IOException
{
/*************************************************************************
SPACE SHIP FLIGHT JFRAME
*************************************************************************/
windowFrame = new JFrame("Space Ship Flight");
windowFrame.setBounds(0, 0, 950, 700);
windowFrame.setBackground(Color.BLACK);
/*************************************************************************
SPACE SHIP FLIGHT SPRITES (FOR DRAWING)
*************************************************************************/
spaceBackground = ImageIO.read(new File("Space (Medium).png"));
// 450 x 374
shipSprite = ImageIO.read(new File("Ship Sprite.png"));
// 64 x 64 png of space ship
/*************************************************************************
SPACE SHIP FLIGHT JPANEL (FOR DRAWING)
*************************************************************************/
SpacePanel spacePanel = new SpacePanel();
windowFrame.add(spacePanel);
/*************************************************************************
SPACE SHIP FLIGHT TIMER
*************************************************************************/
Timer timer = new Timer(10, new AnimationListener(spacePanel));
timer.start();
/*************************************************************************
EVENT HANDLER TO MOVE SPACE SHIP
*************************************************************************/
/*
EventHandler <KeyEvent> moveShip = new EventHandler<KeyEvent> ()
{
#Override
public void handle(KeyEvent event)
{
if (event.getCharacter().equalsIgnoreCase("X"))
{
spacePanel.setX( spacePanel.getX() + 1 );
}
}
};
*/
KeyListener moveShip = new KeyListener()
{
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_RIGHT && spacePanel.getX() < 375)
{
spacePanel.setX( spacePanel.getX() + 5 );
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT && spacePanel.getX() > 0)
{
spacePanel.setX( spacePanel.getX() - 5);
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_UP && spacePanel.getY() > 0)
{
spacePanel.setY( spacePanel.getY() - 5);
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_DOWN && spacePanel.getY() < 700)
{
spacePanel.setY( spacePanel.getY() + 5 );
spacePanel.repaint();
}
if (e.getKeyCode() == KeyEvent.VK_X)
{
System.out.printf("X: %d, Y: %d\n", spacePanel.getX(),
spacePanel.getY());
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
};
windowFrame.addKeyListener(moveShip);
}
/** ANIMATION LISTENER CLASS **/
public static class AnimationListener implements ActionListener
{
private SpacePanel panel;
private Graphics graphics;
public AnimationListener(SpacePanel panel)
{
this.panel = panel;
this.graphics = panel.getGraphics();
}
#Override
public void actionPerformed(ActionEvent e)
{
panel.repaint();
}
}
/** SPACE PANEL SUBCLASS **/
public class SpacePanel extends JPanel
{
// Variables for the space ship's position temporarily placed here
private int x;
private int y;
// Constructor
public SpacePanel()
{
super();
x = 0;
y = 0;
}
// Getters
public int getX()
{
return x;
}
public int getY()
{
return y;
}
// Setters
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
#Override
public void paint(Graphics g)
{
g.drawImage(spaceBackground, 0, 0, this);
g.drawImage(shipSprite, x, y, this);
}
}
}

Why the dot I created is not moving?

I'm trying to move a dot by pressing the right-left keys.
Here is my main:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(500,500);
Graphic graphic=new Graphic();
frame.add(graphic);
}}
This is the graphic class where i created the dot and I implemented KeyListener and ActionListener:
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.JPanel;
import javax.swing.Timer;
public class Graphic extends JPanel implements ActionListener, KeyListener {
private int posX = 220;
private int posY = 300;
private Timer timer;
private int delay = 8;
private int width = 500;
private int height = 500;
public Graphic() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
this.setSize(width, height);
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
g.setColor(Color.GREEN);
g.fillOval(posX, posY, 20, 20);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (posX <= 20) {
posX = 20;
} else {
moveLeft();
}
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (posX >= 460) {
posX = 460;
} else {
moveRight();
}
}
repaint();
}
private void moveRight() {
posX += 20;
}
private void moveLeft() {
posX -= 20;
}
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
In my opinion, this should work...but it doesn't. When I press the left-right keys nothing happens and it looks like it's not "listening" my commands. So, what is wrong with my code?
KeyListener works if the component which has the listener has the focus. JFrame has by default the focus when you display it but not a JPanel.
In the Graphic constructor add simply grabFocus() :
public Graphic() {
addKeyListener(this);
setFocusTraversalKeysEnabled(true);
setFocusable(true);
grabFocus();
timer = new Timer(delay, this);
timer.start();
this.setSize(width, height);
}
EDIT
I have tested on my machine. The problem is that it works randomly as the JFrame needs to be visible if we want that the JPanel grab the focus. Sometimes it is, other times it is not.
SwingUtilities.invokeLater() may solve the problem.
After adding the panel to the JFrame, invoke the code which grabs the focus in a invokeLater() method.
frame.add(graphic);
...
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
graphic.grabFocus();
}
});
You call repaint method of Component class instead of your paint method.

Null Pointer Exception on GUI application using three classes

I'm working on a fairly basic game for myself. New to Java Swing but not to Cpp. Onto the problem at hand.
As I start to run the GUI app, I'm shot with a Null Pointer Exception and given four links where they happen(I use Eclipse as my IDE). But when I look at them I see no problem with the lines or anything around them.
So I came to see if any of you can spot what I can't find.
This class grabs the picture from the source folder and sets up the keys for giving movement.
import java.awt.event.KeyEvent;
import java.awt.Image;
import javax.swing.ImageIcon;
public class SPRITES
{
private int x_sped;
private int y_sped;
private int x;
private int y;
private Image sprite;
public SPRITES()
{
ImageIcon pine = new ImageIcon(this.getClass().getResource("Untitled.png")); //exception here, line 17
sprite = pine.getImage();
x = 0;
y = 0;
}
public void move()
{
x += x_sped;
y += y_sped;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Image getImage()
{
return sprite;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_A)
{
x_sped = -1;
}
if(key == KeyEvent.VK_D)
{
x_sped = 1;
}
if(key == KeyEvent.VK_W)
{
y_sped = -1;
}
if(key == KeyEvent.VK_S)
{
y_sped = 1;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_A)
{
x_sped = 0;
}
if(key == KeyEvent.VK_D)
{
x_sped = 0;
}
if(key == KeyEvent.VK_W)
{
y_sped = 0;
}
if(key == KeyEvent.VK_S)
{
y_sped = 0;
}
}
}
The second one is for getting the frame setting up with completely making the frame and finishing up the making of the movement.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Stage extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private Timer start_stop;
private SPRITES player;
public Stage()
{
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.black);
setDoubleBuffered(true);
player = new SPRITES();
start_stop = new Timer(5, this);
start_stop.start();
}
public void paint(Graphics character)
{
super.paint(character);
Graphics2D G2D = (Graphics2D) character;
G2D.drawImage(player.getImage(), player.getX(), player.getY(), this);
Toolkit.getDefaultToolkit().sync();
character.dispose();
}
public void actionPerformed(ActionEvent arg0)
{
player.move();
repaint();
}
private class TAdapter extends KeyAdapter
{
public void keyReleased(KeyEvent e)
{
player.keyReleased(e);
}
public void keyPressed(KeyEvent e)
{
player.keyPressed(e);
}
}
}
This last one should tie it all together...granted I knew how to fix the exception.
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Framing extends JFrame
{
public Framing()
{
add(new Stage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setLocationRelativeTo(null);
setTitle("FLY");
setResizable(false);
setVisible(true);
}
public static void main(String[] args)
{
new Framing();
}
}
What is causing these exceptions to happen? How can I fix the problem and what should I work on to avoid this happening again?
I think you are misreading the stacktrace from eclipse. All the links except for the first(The one at the top) is the call stack, which show the calls made to the place where you got a nullpointer exception.
Which fit because the code:
new Framing()
Calls
add(new Stage())
which calls
player = new SPRITES();
Which calls
ImageIcon pine = new ImageIcon(this.getClass().getResource("Untitled.png"));
And this is where your nullpointer exception is. My guess is that getResources("Untitled.png"); returns null which then causes the ImageIcon constructor to throw a nullpointer exception.

Detect overlapping objects in java Swing

I am trying to make a program that has a moving ball and a platform that it will sit on. I am new too java and I cant figure out how to detect when 2 swing objects are overlapping. My code it below and I am wondering what the best way is to detect overlapping objects.
KeyDemo.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 600;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Move the Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final WallComponent wc1 = new WallComponent(400, 400);
final BallComponent bc = new BallComponent(400, 300);
panel.add(wc1);
panel.add(bc);
frame.add(panel);
KeyboardController kc = new KeyboardController(bc);
frame.addKeyListener(kc);
frame.setVisible(true);
class AnimationListener implements ActionListener{
public void actionPerformed(ActionEvent event){
bc.tick();
//wc1.checkOverlap(bc);
}
}
ActionListener aListener = new AnimationListener();
final Timer timer = new Timer(1, aListener);
timer.start();
}
}
KeyboardController.java:
import java.awt.*;
import java.awt.event.*;
public class KeyboardController implements KeyListener
{
BallComponent bComp;
public KeyboardController(BallComponent t)
{
bComp = t;
}
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == 38)
{
System.out.println("Pressed Up!");
bComp.moveUp();
}
if(keyCode == 37)
{
System.out.println("Pressed Left!");
bComp.moveLeft();
}
if(keyCode == 39)
{
System.out.println("Pressed Right!");
bComp.moveRight();
}
if(keyCode == 40)
{
System.out.println("Pressed Down!");
bComp.moveDown();
}
}
/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == 38)
{
System.out.println("Released Up!");
bComp.stopY();
}
if(keyCode == 37)
{
System.out.println("Released Left!");
bComp.stopX();
}
if(keyCode == 39)
{
System.out.println("Released Right!");
bComp.stopX();
}
if(keyCode == 40)
{
System.out.println("Pressed Down!");
bComp.stopY();
}
}
public void keyTyped(KeyEvent e) {
}
}
BallComponent.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class BallComponent extends JComponent
{
int xSpeed;
int ySpeed;
int x;
int y;
public BallComponent(int x, int y)
{
super();
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Ellipse2D.Double ball = new Ellipse2D.Double(x-10,y-10,10,10);
g2.setColor(Color.RED);
g2.fill(ball);
g2.draw(ball);
}
public void moveLeft()
{
xSpeed=-1;
}
public void moveRight()
{
xSpeed=1;
}
public void moveUp()
{
ySpeed=-1;
}
public void moveDown()
{
ySpeed=1;
}
public void tick()
{
x=x+xSpeed;
y=y+ySpeed;
repaint();
}
public void stopY()
{
ySpeed=0;
}
public void stopX()
{
xSpeed=0;
}
}
WallComponent.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class WallComponent extends JComponent
{
int x;
int y;
public WallComponent(int x, int y)
{
super();
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Rectangle wall = new Rectangle(x-40,y-40,40,40);
g2.setColor(Color.YELLOW);
g2.fill(wall);
g2.draw(wall);
}
public void checkOverlap(BallComponent bc){
if (this.contains(bc.getLocation())){
bc.stopY();
bc.stopX();
}
}
}
All Swing components have a concept of "bounds". This is a rectangular area within which they are "drawn".
If you are controlling the size and position correctly, you should be able to use the contains method of the Rectangle which is returned from calling Component#getBounds
So you checkOverlap method could look like...
public void checkOverlap(BallComponent bc){
if (getBounds().intersects(bc.getBounds())){
bc.stopY();
bc.stopX();
}
}
You will also want to make sure that you are calling super.paintComponent before performing any custom painting, espeically when using components that extend from JComponent. This will ensure that the Graphics context is prepared for painting correctly...
Updated
There's a cascade of issues. Basically, instead of positing the components within the parent container yourself (which is how I thought you had done it), you've laid each component out to fill the parent container and only "painted" the objects...This makes life more difficult
Instead, if you are going to use components, I would use a null layout (or even possibly use a JLayeredPane as the parent container).
I would then change the physical position of the components, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGame {
public static void main(String[] args) {
new TestGame();
}
public TestGame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(null);
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 600;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Move the Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final WallComponent wc1 = new WallComponent(400, 400);
final BallComponent bc = new BallComponent(400, 300);
panel.add(wc1);
panel.add(bc);
frame.add(panel);
KeyboardController kc = new KeyboardController(bc);
frame.addKeyListener(kc);
frame.setVisible(true);
class AnimationListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
bc.tick();
wc1.checkOverlap(bc);
}
}
ActionListener aListener = new AnimationListener();
final Timer timer = new Timer(1, aListener);
timer.start();
}
});
}
public class KeyboardController implements KeyListener {
BallComponent bComp;
public KeyboardController(BallComponent t) {
bComp = t;
}
/**
* Handle the key pressed event from the text field.
*/
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == 38) {
System.out.println("Pressed Up!");
bComp.moveUp();
}
if (keyCode == 37) {
System.out.println("Pressed Left!");
bComp.moveLeft();
}
if (keyCode == 39) {
System.out.println("Pressed Right!");
bComp.moveRight();
}
if (keyCode == 40) {
System.out.println("Pressed Down!");
bComp.moveDown();
}
}
/**
* Handle the key released event from the text field.
*/
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == 38) {
System.out.println("Released Up!");
bComp.stopY();
}
if (keyCode == 37) {
System.out.println("Released Left!");
bComp.stopX();
}
if (keyCode == 39) {
System.out.println("Released Right!");
bComp.stopX();
}
if (keyCode == 40) {
System.out.println("Pressed Down!");
bComp.stopY();
}
}
public void keyTyped(KeyEvent e) {
}
}
public class BallComponent extends JComponent {
int xSpeed;
int ySpeed;
public BallComponent(int x, int y) {
super();
setBounds(x, y, 10, 10);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double ball = new Ellipse2D.Double(0, 0, 9, 9);
g2.setColor(Color.RED);
g2.fill(ball);
g2.draw(ball);
}
public void moveLeft() {
xSpeed = -1;
}
public void moveRight() {
xSpeed = 1;
}
public void moveUp() {
ySpeed = -1;
}
public void moveDown() {
ySpeed = 1;
}
public void tick() {
int x = getX() + xSpeed;
int y = getY() + ySpeed;
setLocation(x, y);
repaint();
}
public void stopY() {
ySpeed = 0;
}
public void stopX() {
xSpeed = 0;
}
}
public class WallComponent extends JComponent {
public WallComponent(int x, int y) {
super();
setBounds(x, y, 40, 40);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Rectangle wall = new Rectangle(0, 0, 40, 40);
g2.setColor(Color.YELLOW);
g2.fill(wall);
g2.draw(wall);
}
public void checkOverlap(BallComponent bc) {
System.out.println(" me: " + getBounds());
System.out.println("you: " + bc.getBounds());
if (getBounds().intersects(bc.getBounds())) {
bc.stopY();
bc.stopX();
}
}
}
}
Now, you could use "painted" objects, but in that case I would have a virtual concept of a Ball and Wall which you could paint within a single component. These objects would need to provide information about there position and size, which you could, again, check using Rectangle#intersects...
Generally, just try to make a "bounding box" for your objects. This will be the invisible rectangle that goes with the object. Then just do
if(rectangle1.intersects(rectangle2)) ...
The intersects method only works with rectangles, and that's why you need a bounding box.

Categories

Resources