Drawing a Rectangle using MouseListener & MouseMotionListener - java

I've created two packages, Display and paint_core, which contain five Java files: Displayable.java, Drawing.java, NewCordinates.java, OldCordinates.java and Main.java.
I am facing some coordinates issues and the output is not coming as desired. What is wrong with my program?
Main.java
package paint_core;
import Display.Displayable;
public class Main {
public Main() {
}
public static void main(String[] args) {
new Displayable();
}
}
Displayable.java
package Display;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
public class Displayable extends JFrame implements MouseListener,MouseMotionListener{
Drawing dr;
int x,y;
OldCordinates op;
public Displayable()
{
setVisible(true);
dr = new Drawing();
add(dr);
dr.addMouseListener(this);
dr.addMouseMotionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseDragged(MouseEvent e)
{
NewCordinates np = new NewCordinates();
np.setX(x);
np.setY(y);
np.setW(e.getX()-x);
np.setH(e.getY()-y);
op= dr.setXY(np.getX(),np.getY(),np.getW(),np.getH(),Color.RED,op);
}
public void mouseMoved(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e) {
x=e.getX();
y=e.getY();
op = new OldCordinates();
op.setX(x);
op.setY(y);
op.setW(x);
op.setH(y);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
Drawing.java
package Display;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Drawing extends JPanel
{
private int x,y,w,h;
Color r;
OldCordinates op;
public OldCordinates setXY(int x,int y,int w,int h,Color r,OldCordinates op)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.r = r;
this.op = op;
//System.out.println("Old Cordinates" + op.getW()+" "+op.getY());
repaint();
op.setH(h);
op.setW(w);
//System.out.println("New Cordinates" + w+" "+h);
return op;
}
#Override
public void paint(Graphics g) {
g.drawRect(op.getX(),op.getY(),op.getW(),op.getH());
g.setColor(r);
g.drawRect(x,y,w,h);
}
}
OldCordinates.java
package Display;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Drawing extends JPanel
{
private int x,y,w,h;
Color r;
OldCordinates op;
public OldCordinates setXY(int x,int y,int w,int h,Color r,OldCordinates op)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.r = r;
this.op = op;
//System.out.println("Old Cordinates" + op.getW()+" "+op.getY());
repaint();
op.setH(h);
op.setW(w);
//System.out.println("New Cordinates" + w+" "+h);
return op;
}
#Override
public void paint(Graphics g) {
//g.drawRect(op.getX(),op.getY(),op.getW(),op.getH());
g.setColor(r);
g.drawRect(x,y,w,h);
}
}
NewCordinates.java
package Display;
public class NewCordinates {
private int x;
private int y;
private int w;
private int h;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
}

You should override paintComponent instead of paint. If this is not your problem, please give more details

Related

Detecting Collision between two filled Rectangles

I'm trying to make it print out "Game over" when the Green Square(Cuboid) runs over/into the blue(CuboidKiller) one.
GAME class:
package plugin.dev.wristz;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class Game extends JFrame {
private static final long serialVersionUID = 294623570092988970L;
public static ArrayList<CuboidKiller> killers;
public static int h = 1024, w = 768;
public static Game game;
public static Graphics graphics, g2;
public static Image image;
public static Cuboid cuboid;
public Game(String title) {
setTitle(title);
setSize(1024, 768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
setLocationRelativeTo(null);
addKeyListener(new KeyHandler(cuboid));
g2 = getGraphics();
paint(g2);
}
public static void main(String[] args) {
cuboid = new Cuboid();
Thread cubi = new Thread(cuboid);
cubi.start();
killers = new ArrayList<CuboidKiller>();
CuboidKiller a = new CuboidKiller(new Random().nextInt(h), new Random().nextInt(w), new Random().nextInt(50) + 20);
killers.add(a);
game = new Game("Killer Cuboids");
}
#Override
public void paint(Graphics g) {
image = createImage(getWidth(), getHeight());
graphics = image.getGraphics();
paintComponent(graphics);
g.drawImage(image, 0, 0, this);
}
public void paintComponent(Graphics g) {
checkGameOver();
cuboid.draw(g);
for (CuboidKiller killer : killers)
killer.draw(g);
repaint();
}
public void checkGameOver() {
for (CuboidKiller killer : killers)
if (killer.isTouching(cuboid))
System.out.println("Game over!");
}
public int getH() {
return h;
}
public void setH(int wh) {
h = wh;
}
public int getW() {
return w;
}
public void setW(int ww) {
w = ww;
}
}
Cuboid class:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
#SuppressWarnings("static-access")
public class Cuboid implements Runnable {
private int x, y, xDirection, zDirection;
public Cuboid() {
this.x = 799;
this.y = 755;
}
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(x, y, 25, 25);
}
public void move() {
x += xDirection;
y += zDirection;
if (x <= 10)
x = 0 + 10;
if (y <= 35)
y = 0 + 35;
if (x >= 1024 - 35)
x = 1024 - 35;
if (y >= 768 - 35)
y = 768 - 35;
}
public void keyPressed(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(-5);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(5);
}
if (keyCode == ev.VK_UP) {
setZDirection(-5);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(5);
}
}
public void keyReleased(KeyEvent ev) {
int keyCode = ev.getKeyCode();
if (keyCode == ev.VK_LEFT) {
setXDirection(0);
}
if (keyCode == ev.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == ev.VK_UP) {
setZDirection(0);
}
if (keyCode == ev.VK_DOWN) {
setZDirection(0);
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(5);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getXDirection() {
return xDirection;
}
public void setXDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getZ() {
return y;
}
public void setZ(int z) {
this.y = z;
}
public int getZDirection() {
return zDirection;
}
public void setZDirection(int zDirection) {
this.zDirection = zDirection;
}
}
Cuboid Killer:
package plugin.dev.wristz;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
public class CuboidKiller {
private int x, y, radius;
private HashMap<Integer, Integer> points;
public CuboidKiller(int x, int y, int radius) {
this.points = new HashMap<Integer, Integer>();
setPoints();
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, radius, radius);
}
public void setPoints() {
this.points.put(x, y);
this.points.put(x + radius, y);
this.points.put(x + radius, y - radius);
this.points.put(x, y - radius);
}
public boolean isTouching(Cuboid cuboid) {
boolean result = true;
//int a = cuboid.getX(), b = cuboid.getZ();
result = true;
return result;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public HashMap<Integer, Integer> getPoints() {
return points;
}
public void setPoints(HashMap<Integer, Integer> points) {
this.points = points;
}
}
Well, there are two approaches. Either you write it yourself, or you just use what Java 8 provides.
This guy has a very nice explanation on how to detect collision between two rectangles: Java check if two rectangles overlap at any point
But if I were the one writing it, I would just have both classes contain a Rectangle object (http://docs.oracle.com/javase/8/docs/api/java/awt/Rectangle.html), and just call the intersects() function provided by Rectangle. :-)

Why won't my KeyPressed method run

I am trying to write a game in which a character moves around and jumps from block to block in order to get to the end. But the problem I'm facing is that my KeyPressed method won't run. I've tried putting a System.out.println("Hi"); in the method to see if it even starts running. But the "Hi" never showed up. This is my code.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Driver extends Applet implements KeyListener
{
private int X = 0;
private int Y = 250;
private int sizeX = 25;
private int sizeY = 25;
private boolean start=false;
public int getX()
{
return X;
}
public void setX(int x)
{
X = x;
}
public int getY()
{
return Y;
}
public void setY(int y)
{
Y = y;
}
public int getsizeY()
{
return sizeY;
}
public void setsizeY(int sizey)
{
sizeY = sizey;
}
public int getsizeX()
{
return sizeX;
}
public void setsizeX(int sizex)
{
sizeX = sizex;
}
public void init()
{
this.addKeyListener(this);
setSize(300, 300);
setFocusable(false);
requestFocus();
}
public void paint(Graphics g)
{
init();
map map1 = new map();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 300, 300);
g.setColor(Color.black);
map1.paint(g);
g.fillRect(X, Y, sizeX, sizeY);
start=true;
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
if(start)
{
System.out.println("Hi");
if(e.getKeyChar() == 'w')
{
System.out.println("Hi");
setY(getY()-1);
}
if(e.getKeyChar() == 'd')
{
setX(getX()+1);
}
if(e.getKeyChar() == 'a')
{
setX(getX()-1);
}
if(e.getKeyChar() == 's')
{
setY(getY()+1);
}
repaint();
}
}
}
I am still learning how to code so please don't be mean, but if you could help that would be great!

mouseMoved not called while mousePressed has been called

My mouseMoved simply doesn't get called when mousePressed has been called, but it gets called normally when mousePressed didn't. If I move my mouse while I press a mouse button mouseMoved doesn't get called.
package src.game.main.gui_hud;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import javax.swing.SwingUtilities;
import src.game.main.Game;
public class Slider {
private Color lc,hc,fc;
private int x,y;
private int w,h;
private Runnable change;
private int lineY;
private double value = 100;
private volatile boolean canMove;
public Slider(Color bgColor,Color filledColor,Color handlerColor,Runnable onValueChange,int x,int y,int w,int h,int lineY) {
setLc(bgColor);
setHc(handlerColor);
setFc(filledColor);
change = onValueChange;
this.x = x;
this.y = y;
this.w = w;
this.h = w;
this.lineY = lineY;
}
public void render(Graphics gt) {
Graphics2D g = (Graphics2D) gt.create(x, y, w, h);
g.setColor(getLc());
g.fillRoundRect(10, y/2-lineY, w-10, lineY, 10, 10);
g.setColor(getFc());
g.fillRoundRect(10, y/2-lineY, (int) ((value*w)/100)-10, lineY, 10, 10);
g.setColor(getHc());
g.fillRoundRect((int)((value*w)/100)-6, y/2-20, 5, 30, 10, 10);
}
public void tick() {
value = Game.clamp(value, 0, 100);
System.out.println(canMove);
}
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if (new RoundRectangle2D.Double(x+ ((int)((value*w)/100)-6), y + (y/2-20), 5, 30, 10, 10).contains(p)) {
canMove = SwingUtilities.isLeftMouseButton(e);
}
}
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
canMove = false;
}
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX());
Point p = e.getPoint();
if(canMove) System.out.println("LOL");
}
public Color getHc() {
return hc;
}
public Slider setHc(Color hc) {
this.hc = hc;
return this;
}
public Color getLc() {
return lc;
}
public Slider setLc(Color lc) {
this.lc = lc;
return this;
}
public int getX() {
return x;
}
public Slider setX(int x) {
this.x = x;
return this;
}
public int getY() {
return y;
}
public Slider setY(int y) {
this.y = y;
return this;
}
public int getW() {
return w;
}
public Slider setW(int w) {
this.w = w;
return this;
}
public int getH() {
return h;
}
public Slider setH(int h) {
this.h = h;
return this;
}
public double getValue() {
return value;
}
public Slider setValue(double v) {
this.value = v;
return this;
}
public Color getFc() {
return fc;
}
public Slider setFc(Color fc) {
this.fc = fc;
return this;
}
Based on the code in the mousePressed handler, you're trying to do some sort of drag-rectangle, although I can't be certain.
The mouseMoved messages will keep happening until you get a mousePressed event. Once you've received the mousePressed event you will then start to receive mouseDragged events until the receipt of a mouseReleased event. After that point you will start to receive mouseMoved events again.
This is intended to allow differentiating between just moving the mouse and dragging with one of the buttons pressed.

rotating around a circle without affecting movement

I'm trying to create a rectangle that can freely move around the screen whilst also rotating so that it faces a circle or certain point.
My current state makes the object move in a very bizarre fashion and can't seem to fix it.
import javax.swing.JFrame;
public class Start {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("Minigame");
f.setContentPane(new Panel());
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
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 Panel extends JPanel implements ActionListener, KeyListener{
private Timer timer;
private Graphics2D g2d;
private Planet planet;
private Player player;
private double rotation=0;
private int dx=0;
private int dy=0;
public Panel(){
setFocusable(true);
requestFocus();
planet = new Planet(100,100,100);
player = new Player(200,200,20,50);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g2d=(Graphics2D)g;
g2d.fillOval(planet.getX(), planet.getY(), planet.getRadius(), planet.getRadius());
g2d.setColor(Color.BLUE);
g2d.rotate(rotation,planet.centerX(),planet.centerY());
g2d.fillRect(player.getX(), player.getY(), player.getWidth(),player.getHeight());
g2d.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
rotation=Math.atan2(player.centerX()-planet.centerX(), player.centerY()-planet.centerY());
player.x+=dx;
player.y+=dy;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -5;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 5;
}
if (key == KeyEvent.VK_UP) {
dy = -5;
}
if (key == KeyEvent.VK_DOWN) {
dy = 5;
}
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
if (dx==-5)
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
if (dx==5)
dx = 0;
}
if (key == KeyEvent.VK_UP) {
if (dy==-5)
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
if (dy==5)
dy = 0;
}
}
#Override
public void addNotify(){
super.addNotify();
timer=new Timer(10,this);
timer.start();
addKeyListener(this);
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
public class Planet{
public int x;
public int y;
private int radius;
public Planet(int x,int y,int radius){
this.x=x;
this.y=y;
this.radius=radius;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getRadius(){
return radius;
}
public int centerX(){
return x+(radius/2);
}
public int centerY(){
return y+(radius/2);
}
}
public class Player {
public int x;
public int y;
private int width;
private int height;
public Player(int x,int y,int width,int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getHeight(){
return height;
}
public int getWidth(){
return width;
}
public int centerX(){
return x+(width/2);
}
public int centerY(){
return y+(height/2);
}
}
This is working for me. I changed the sign of the angle, and the way that the player is drawn.
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g2d=(Graphics2D)g;
// Draw planet
g2d.fillOval(planet.getX(), planet.getY(), planet.getRadius(), planet.getRadius());
// Draw player
g2d.setColor(Color.BLUE);
g2d.rotate(rotation, player.centerX(), player.centerY());
Rectangle rect = new Rectangle(player.centerX()-(player.getWidth()/2), player.centerY()-(player.getHeight()/2), player.getWidth(),player.getHeight());
g2d.draw(rect);
g2d.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
rotation=Math.atan2(+player.centerX()-planet.centerX(), - player.centerY()+planet.centerY());
player.x+=dx;
player.y+=dy;
repaint();
}
I haven't checked the calculation of the rotation, but I think fillOval should use twice the radius to draw the planet:
g2d.fillOval(planet.getX(), planet.getY(), planet.getRadius()*2, planet.getRadius()*2);

JFrame add only one class

I'am making a game, and my JFrame add only one class, i don't getting error, but one of two classes dosen't show. I am try to make JFrame frame 2 = new JFrame();, but nothing.
Game.java:
import java.awt.Component;
import javax.swing.JFrame;
public class Game{
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final String TITLE = "Game Dev [ Week #1 ]";
public static void main(String[] args){
JFrame frame = new JFrame();
Player player = new Player();
Rabbit rabbit = new Rabbit();
// Draw on the map
player.setPlayer(250,250);
rabbit.setRabbit(200,200);
// Draw on the map
frame.add(player);
frame.add(rabbit); // Add only this
// Window
frame.setVisible(true);
frame.setSize(WIDTH,HEIGHT);
frame.setTitle(TITLE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Player.java:
public class Player extends JPanel implements ActionListener, KeyListener{
// Varibles
Timer time = new Timer(5, this);
static int x; double velX = 0;
static int y; double velY = 0;
private BufferedImage player;
boolean W = false;
boolean A = false;
boolean S = false;
boolean D = false;
public void setPlayer(int x, int y){
this.x = x;
this.y = y;
}
public Player(){
time.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
try {
player = ImageIO.read(getClass().getResourceAsStream("/Player.png"));
} catch (IOException e){
e.printStackTrace();
}
}
// Draw player
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(player, (int)x, (int)y, 100, 100, null);
}
// Set the start up position of player
public void actionPerformed(ActionEvent e){
x += velX;
y += velY;
repaint();
}
// Functions for keyEvent
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_W) // UP
velY = -0.5;
if(key == KeyEvent.VK_A) // LEFT
velX = -0.5;
if(key == KeyEvent.VK_S) // DOWN
velY = 1.5;
if(key == KeyEvent.VK_D) // RIGHT
velX = 1.5;
}
public void keyTyped(KeyEvent e){}
// IF any key released
public void keyReleased(KeyEvent arg0) {
velX = 0;
velY = 0;
W = false;
A = false;
S = false;
D = false;
}
}
Rabbit.java:
public class Rabbit extends JPanel implements ActionListener{
static int x; double velX = 0;
static int y; double velY = 0;
BufferedImage rabbit;
public void setRabbit(int x, int y){
this.x = x;
this.y = y;
}
public Rabbit(){
try {
rabbit = ImageIO.read(getClass().getResourceAsStream("/Rabbit.png"));
} catch (IOException e){
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(rabbit, (int)x, (int)y, 100, 100, null);
}
public void actionPerformed(ActionEvent e){
x += velX;
y += velY;
repaint();
}
}
What's happening is that the JFrame is not combining the graphics for Player and Rabbit; rather, it is placing the player as a panel, and then placing the rabbit. So, the player and the rabbit are always separated. What you want is the Player and Rabbit classes NOT to extend JPanel, but to have a method called paint(Graphics). That way, you can make a class called GamePanel that extends JPanel, and create new methods setPlayer(Player) and setRabbit(Rabbit). The GamePanel class should look like this:
public class GamePanel extends JPanel {
Player player;
Rabbit rabbit;
public void setPlayer(Player player) {
this.player = player;
}
public void setRabbit(Rabbit rabbit) {
this.rabbit = rabbit;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
player.paint(g);
rabbit.paint(g);
}
}
and your Player class should look like this:
public class Player {
public void paint(Graphics g) {
// How to paint the graphics in the player class
}
}
and your Rabbit class should look the same, except as public class Rabbit.
Hope that helps!
EDIT: Full Script
package game;
import java.awt.Graphics;
public interface Displayable {
public void paint(Graphics graphics);
}
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Rabbit implements Displayable {
private int x, y;
private Image image;
public Rabbit(int x, int y) throws IOException {
this.x = x;
this.y = y;
this.image = ImageIO.read(new File("RABBIT_FILE")); // Replace
// "RABBIT_FILE"
// with the image
// file you have
}
public void paint(Graphics graphics) {
graphics.drawImage(this.image, this.x, this.y, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
return false;
}
});
/**
* Optional: JDK 8 only:
*
* graphics.drawImage(this.image, this.x, this.y, (Image img, int
* infoflags, int x0, int y0, int width0, int height0) -> false);
* //Lambda Expression
*/
}
public void setCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player implements Displayable {
private int x, y;
private Image image;
public Player(int x, int y) throws IOException {
this.x = x;
this.y = y;
this.image = ImageIO.read(new File("PLAYER_FILE")); // Replace
// "PLAYER_FILE"
// with the image
// file you have
}
public void paint(Graphics graphics) {
graphics.drawImage(this.image, this.x, this.y, new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y,
int width, int height) {
return false;
}
});
/**
* Optional: JDK 8 only:
*
* graphics.drawImage(this.image, this.x, this.y, (Image img, int
* infoflags, int x0, int y0, int width0, int height0) -> false);
* //Lambda Expression
*/
}
public void setCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
}
package game;
import java.awt.Graphics;
import javax.swing.JPanel;
public final class GamePanel extends JPanel {
private static final long serialVersionUID = -385535147711891740L;
private Player player;
private Rabbit rabbit;
public void setPlayer(Player player) {
this.player = player;
}
public void setRabbit(Rabbit rabbit) {
this.rabbit = rabbit;
}
public GamePanel(Player player, Rabbit rabbit) {
this.setPlayer(player);
this.setRabbit(rabbit);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.player.paint(g);
this.rabbit.paint(g);
}
}
package game;
import javax.swing.JFrame;
public final class Main {
public static void main(String... args) {
try {
JFrame frame = new JFrame("Player & Rabbit Game"); // Or whatever
// title
// you have in mind
GamePanel panel = new GamePanel(new Player(0, 0), new Rabbit(0, 0));
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
frame.setExtendedState(6);
} catch (Exception e) {
// Handle Exception if file is corrupted, unable to be read to an
// image, or does not exist
}
}
}

Categories

Resources