Setting up javax.swing.Timer - java

Ok I'm doing a project and the image is supposed to move around randomly and when the user clicks on the image it's supposed to count how many times the click on it. From there on it keeps moving until they x out. However, I made the mistake of making the image move AFTER they click on it, so when the program starts the image isn't already moving. I need it to move from the beginning of the program.
Attached here because for whatever reason, stack overflow keeps saying I formatted wrong.
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
// Zombie class
public class Zombie {
//declare variables
private int x;
private int y;
private int size;
private Image image;
//constructor
public Zombie(int xIn, int yIn, String imagePath) {
x = xIn;
y = yIn;
size = Settings.DEFAULT_SIZE;
setImage(imagePath);
}
//getter for x
public int getX() {
return x;
}
//getter for y
public int getY() {
return y;
}
//setter for x
public void setX(int x) {
this.x = x;
}
//setter for y
public void setY(int y) {
this.y = y;
}
//drawImage method
public void update(Graphics g) {
g.drawImage(image, x, y, size, size, null);
}
//try catch exception, if image isn't found
public void setImage(String imagePath) {
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException ioe) {
System.out.println("Unable to load image file.");
}
}
}
public class Settings {
//adjusts the width and height of the creature
public static final int WIDTH = 500;
public static final int HEIGHT = 300;
public static final int DEFAULT_SIZE = 50;
//image name
public static final String ZOMBIE_IMAGE = "zombie.png";
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.util.Random;
class Controller implements MouseListener {
//declares variables
Zombie zombie;
View view;
private int count = 0;
Controller() {
//System.out.println ("Controller()");
}
public void addZombie(Zombie z){
//System.out.println("Controller: adding zombie");
this.zombie = z;
}
public void addView(View v){
//System.out.println("Controller: adding view");
this.view = v;
}
public void mousePressed(MouseEvent e) {
//System.out.println("Controller sees mouse pressed: acting on Model");
int prevX = e.getX();
int prevY = e.getY();
prevX -= zombie.getX();
prevY -= zombie.getY();
if((prevX > 0 && prevX < Settings.DEFAULT_SIZE) &&
(prevY > 0 && prevY < Settings.DEFAULT_SIZE)) {
//System.out.println("Got Zombie.");
Random r = new Random();
zombie.setX(r.nextInt(view.getWidth() - Settings.DEFAULT_SIZE));
zombie.setY(r.nextInt(view.getHeight() - Settings.DEFAULT_SIZE));
++count;
}
}
public int getCount() {
return count;
}
//mouse events
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void update(Graphics g) {
zombie.update(g);
}
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.util.Random;
public class View implements ActionListener {
private JFrame frame;
Controller controller;
public static void main(String[] args) {
Zombie zombie = new Zombie(Settings.WIDTH/2, Settings.HEIGHT/2, Settings.ZOMBIE_IMAGE);
View view = new View();
Controller myController = new Controller();
myController.addZombie(zombie);
myController.addView(view);
view.addController(myController);
new Timer(500, view).start();
}
private class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
controller.update(g);
revalidate();
}
}
private MyPanel panel;
View() {
//System.out.println("View()");
frame = new JFrame("Catch The Zombie");
// Create a panel to contain a label, a text box, and a button
panel = new MyPanel();
frame.add(panel);
frame.setSize(Settings.WIDTH, Settings.HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
// TODO Auto-generated method stub
System.out.println("Zombie was caught " + controller.getCount() + "times");
}
});
}
public void revalidate() {
}
public void addController(Controller controller){
//System.out.println("View : adding controller");
this.controller = controller;
frame.getContentPane().addMouseListener((MouseListener) controller);
}
public int getWidth() {
return frame.getWidth();
}
public int getHeight() {
return frame.getHeight();
}
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}

Related

My keybinding didn't do its actionPerformed in JPanel

I've added keybinding on one of my JPanels. The problem is this keybinding didn't do its "actionPerformed". Even though I put a sysout in the actionPerformed, nothing was outputted on the console. Can someone help me with this problem? I've already tried to disable my buttons, but still my keybinding doesn't work.
package project.fin;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.awt.event.*;
import javax.swing.*;
//Panel for my game
public class GamePlayPanel extends JPanel{
private Image current;
private Baby bayi;
public GamePlayPanel(String img) {
Dimension size = new Dimension(1200, 500);
this.setPreferredSize(size);
this.setMaximumSize(size);
this.setMinimumSize(size);
this.setSize(size);
this.setLayout(null);
//An baby object
bayi = new Baby(100, 410, 5);
//this is where my keyBinding initialized
bayi.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0), "moveRight");
bayi.getActionMap().put("moveRight", new Move_it(1));
}
//this is the action class that i want to put in my keybinding
private class Move_it extends AbstractAction{
int code;
public Move_it(int code) {
this.code=code;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("test\n");
if (this.code==1) {
bayi.MoveRight();
}
repaint();
}
}
//To draw my baby
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
bayi.draw(g);
}
}
This is my baby class:
package project.fin;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.event.*;
public class Baby extends JComponent{
float x, y;
float speed;
Image current;
private List <Image> ImgPool;
private int Current;
public Baby(float x, float y, float speed) {
// TODO Auto-generated constructor stub
this.x = x;
this.y = y;
this.speed = speed;
ImgPool = new ArrayList<Image>();
//These are just some images that i use to build my moving baby
ImgPool.add(new ImageIcon("baby1_50.png").getImage());
ImgPool.add(new ImageIcon("baby2_50.png").getImage());
ImgPool.add(new ImageIcon("baby1_50.png").getImage());
ImgPool.add(new ImageIcon("baby3_50.png").getImage());
this.current = ImgPool.get(0);
this.Current = 0;
}
//The action that i want my baby to do when a key is pressed
public void MoveRight() {
if (x>600) return;
this.x+=speed;
if (this.Current==3)this.Current=0;
else
this.Current++;
this.current = this.ImgPool.get(Current);
}
public void draw(Graphics g) {
g.drawImage(this.current, (int)this.x, (int)this.y, null);
}
}
Baby isn't attached to the component hierarchy and therefore won't receive any key events. In fact, the design doesn't make sense. There's no need for Bady to extend from JPanel at all.
Instead, make use of the GamePlayPanel directly
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.*;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GamePlayPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GamePlayPanel extends JPanel {
private Baby bayi;
public GamePlayPanel() {
//An baby object
bayi = new Baby(100, 410, 5);
//this is where my keyBinding initialized
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveRight");
getActionMap().put("moveRight", new Move_it(1));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 500);
}
//this is the action class that i want to put in my keybinding
private class Move_it extends AbstractAction {
int code;
public Move_it(int code) {
this.code = code;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("test\n");
if (this.code == 1) {
bayi.moveRight();
}
repaint();
}
}
//To draw my baby
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
bayi.draw(g);
}
}
public class Baby {
float x, y;
float speed;
Image current;
private List<Image> ImgPool;
private int Current;
public Baby(float x, float y, float speed) {
// TODO Auto-generated constructor stub
this.x = x;
this.y = y;
this.speed = speed;
ImgPool = new ArrayList<Image>();
//These are just some images that i use to build my moving baby
ImgPool.add(new ImageIcon("baby1_50.png").getImage());
ImgPool.add(new ImageIcon("baby2_50.png").getImage());
ImgPool.add(new ImageIcon("baby1_50.png").getImage());
ImgPool.add(new ImageIcon("baby3_50.png").getImage());
this.current = ImgPool.get(0);
this.Current = 0;
}
//The action that i want my baby to do when a key is pressed
public void moveRight() {
if (x > 600) {
return;
}
this.x += speed;
if (this.Current == 3) {
this.Current = 0;
} else {
this.Current++;
}
this.current = this.ImgPool.get(Current);
}
public void draw(Graphics g) {
g.drawImage(this.current, (int) this.x, (int) this.y, null);
}
}
}

JComponent not draggable under GridBagConstraints

I'm currently making a puzzle game, my design is to have the puzzle(a 3*3 Board)show up on top, and my nine pieceComponents on the bottom in a row as my original state, I want to be able to drag my pieceComponents on to the board so I have them in side the same JPanel. I was suggested to use GridBagConstraints for this to happen, however, for my puzzle board this is a giant space on top, and only the last PieceComponent I added to the screen shows up, also the I believe it is the GridBagConstraints that prevented me from using my mouse to drag the PieceComponents(which I have made draggable),
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
public class Display extends JComponent {
private PuzzleDisplay puzzle;
private JFrame frame;
private static List<PieceComponent> pieces = new ArrayList<PieceComponent>();
private JPanel puzzlePanel;
private GridBagConstraints gbc = new GridBagConstraints();
/**
* Launch the application.
*/
public static void main(String[] args) {
Display d = new Display();
d.GUI();
}
/**
* Create the application.
*/
public Display() {
puzzle = new PuzzleDisplay();
}
private void PuzzlePanel() {
puzzlePanel = new JPanel();
puzzlePanel.setLayout(new GridBagLayout());
gbc.gridx=0;
gbc.gridy =0;
puzzlePanel.add(puzzle, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
gbc.gridx = 2;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
gbc.gridx = 3;
gbc.gridy = 1;
puzzlePanel.add(puzzle.getPieces().get(0), gbc);
puzzlePanel.setVisible(true);
}
public void GUI() {
frame = new JFrame("Puzzle");
frame.setVisible(true);
frame.setSize(850, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PuzzlePanel();
frame.add(puzzlePanel, BorderLayout.CENTER);
}
}
this is my PieceComponent class, I made it draggable.
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
public class PieceComponent extends JComponent {
private Piece piece;
private BufferedImage myImage;
private volatile int screenX = 0;
private volatile int screenY = 0;
private volatile int myX = 0;
private volatile int myY = 0;
public PieceComponent(Side top, Side right, Side bottom, Side left, String path) {
piece = new Piece(top, right, bottom, left);
try {
myImage = ImageIO.read((new FileInputStream(path)));
} catch (IOException exp) {
exp.printStackTrace();
}
addMouseListener(new MouseListener() {
#Override
public void mousePressed(MouseEvent e) {
screenX = e.getXOnScreen();
screenY = e.getYOnScreen();
myX = getX();
myY = getY();
}
#Override
public void mouseClicked(MouseEvent e) {
piece.rotateClockwise();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
int deltaX = e.getXOnScreen() - screenX;
int deltaY = e.getYOnScreen() - screenY;
setLocation(myX + deltaX, myY + deltaY);
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
//returns the chosen side
public Side getSide(Direction direction) {
return piece.getSide(direction);
}
public Piece getPiece() {
return piece;
}
public int getHeight() {
return myImage.getHeight();
}
public int getWidth() {
return myImage.getWidth();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (myImage != null) {
AffineTransform trans = new AffineTransform();
trans.translate(getWidth() / 2, getHeight() / 2);
trans.rotate(piece.getOrientation() * Math.PI / 2);
trans.translate(-myImage.getWidth() / 2, -myImage.getHeight() / 2);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(myImage, trans, null);
}
}
public void rotateClockwise() {
piece.rotateClockwise();
}
This is my PuzzleDisplay
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
public class PuzzleDisplay extends JComponent{
private Puzzle puzzle;
private JFrame frame;
private List<PieceComponent> pieceComponents = new ArrayList<PieceComponent>();
private List<Piece> pieces = new ArrayList<Piece>();
/**
* Create the application.
*/
public PuzzleDisplay() {
pieceComponents.add(new PieceComponent(Side.SPADE_OUT, Side.HEART_OUT, Side.DIAMOND_IN, Side.SPADE_IN, "res/piece_1.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.DIAMOND_OUT, Side.CLUB_IN, Side.HEART_IN, "res/piece_2.png"));
pieceComponents.add(new PieceComponent(Side.HEART_OUT, Side.CLUB_OUT, Side.CLUB_IN, Side.SPADE_IN, "res/piece_3.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.DIAMOND_OUT, Side.SPADE_IN, Side.SPADE_IN, "res/piece_4.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.CLUB_OUT, Side.HEART_IN, Side.SPADE_IN, "res/piece_5.png"));
pieceComponents.add(new PieceComponent(Side.HEART_OUT, Side.DIAMOND_OUT, Side.DIAMOND_IN, Side.HEART_IN, "res/piece_6.png"));
pieceComponents.add(new PieceComponent(Side.CLUB_OUT, Side.DIAMOND_OUT, Side.HEART_IN, Side.DIAMOND_IN, "res/piece_7.png"));
pieceComponents.add(new PieceComponent(Side.SPADE_OUT, Side.HEART_OUT, Side.CLUB_IN, Side.HEART_IN, "res/piece_8.png"));
pieceComponents.add(new PieceComponent(Side.DIAMOND_OUT, Side.SPADE_OUT, Side.SPADE_IN, Side.DIAMOND_IN, "res/piece_9.png"));
for(int i=0; i<pieceComponents.size(); i++) {
pieces.add(pieceComponents.get(i).getPiece());
}
puzzle = new Puzzle(3, pieces);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int imageSize = pieceComponents.get(0).getHeight();
int boardBuffer = (getWidth()-3*imageSize)/2;
for(int i=0; i<puzzle.getCols(); i++) {
for(int j=0; j<puzzle.getRows(); j++) {
g2d.drawRect(i*imageSize, j*imageSize, imageSize, imageSize);
}
}
}
//returns the list of all pieces
public List<PieceComponent> getPieces(){
return pieceComponents;
}
//Fills the puzzle with the correct solution
public void solve() {
puzzle.solve();
}
//Determines whether the puzzle has been completed
public boolean isSolved() {
return puzzle.isSolved();
}
//Determines whether a piece will fit at the specified
//location
public boolean doesFit(PieceComponent pc, int row, int col) {
return puzzle.doesFit(pc.getPiece(), row, col);
}
//returns the Piece at the specified location
public Piece getPiece(int row, int col) {
return puzzle.getPiece(row, col);
}
//replaces a Piece at the given location and returns the old Piece
public Piece setPiece(Piece piece, int row, int col) {
return puzzle.setPiece(piece, row, col);
}
//removes and returns the Piece at the given location
public Piece removePiece(int row, int col) {
return removePiece(row, col);
}
//Clears the board and puts all pieces back into the piece list
public void reset() {
puzzle.reset();
}
//returns a List of any pieces not already on the board
public List<Piece> getUnused(){
return puzzle.getUnused();
}
//returns the number of rows
public int getRows() {
return puzzle.getRows();
}
//returns the number of columns
public int getCols() {
return puzzle.getCols();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(pieceComponents.get(0).getHeight()*3, pieceComponents.get(0).getHeight()*3);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
PuzzleDisplay d = new PuzzleDisplay();
JFrame frame = new JFrame("Puzzle");
frame.setVisible(true);
frame.setSize(1250, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(d);
}
}

Error when using java packages

I am writing a game. Its directory tree is basically like this:
ShootGame------>game----------------------->input--------------------------------->InputHandler.class
|-->ShooterGame.class | |-->InputHandler.java
|-->ShooterGame.java |---->player-------------->Player.class
| |-->Player.java
|---->scenario---
|-->Block.class
|-->Block.java
I hope you understand my diagram, but the point is: the "game" folder has 3 folders inside it, "input","player","scenario".
Inside "InputHandler.java", I have declared package game.input.
Inside "Player.java", I have declared package game.player.
And inside "Block.java", I have declared package game.scenario.
So far, so good.
But when, in the Player.java, i do import game.input.InputHandler, it says "package game.input does not exist", even though I have already declared "game.input".
What have I done wrong here? If you need the codes inside the files, please leave a comment. I am not posting them here because I think the main problem I have is the package and import logic.
Thanks.
Edit:
Code
InputHandler.java
package game.input;
import java.awt.Component;
import java.awt.event.*;
public class InputHandler implements KeyListener{
static boolean[] keys = new boolean[256];
public InputHandler(Component c){
c.addKeyListener(this);
}
public boolean isKeyDown(int keyCode){
if (keyCode > 0 && keyCode < 256){
return keys[keyCode];
}
return false;
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() > 0 && e.getKeyCode() < 256){
keys[e.getKeyCode()] = true;
}
}
public void keyReleased(KeyEvent e){
if (e.getKeyCode() > 0 && e.getKeyCode() < 256){
keys[e.getKeyCode()] = false;
}
}
public void keyTyped(KeyEvent e){}
}
Player.java
package game.player;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.net.URL;
import java.awt.event.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import game.input.InputHandler;
public class Player{
private BufferedImage sprite;
public int x, y, width, height;
private final double speed = 5.0d;
public Player(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
try{
URL url = this.getClass().getResource("ship.png");
sprite = ImageIO.read(url);
} catch(IOException e){}
}
public void keyPlayer(double delta, InputHandler i){
if(i.isKeyDown(KeyEvent.VK_D)){
if(this.x>=1240) return;
else this.x+=speed*delta;
}
if(i.isKeyDown(KeyEvent.VK_A)){
if(this.x<=0) return;
else this.x-=speed*delta;
}
}
public void update(InputHandler inputP){
keyPlayer(1.7, inputP);
}
public void Draw(Graphics a){
a.drawImage(sprite,x,y,width,height,null);
}
public Rectangle getBounds(){
return new Rectangle(x,y,width,height);
}
}
Block.java
package game.scenario;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.net.URL;
import java.awt.event.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.Timer;
import java.util.TimerTask;
public class Block{
private Timer timer;
private BufferedImage sprite;
private final int t = 1;
public int x, y, width, height;
public Block(int x, int y, int width, int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
try{
URL url = this.getClass().getResource("meteor.png");
sprite = ImageIO.read(url);
} catch(IOException e){}
}
public void Draw(Graphics g){
g.drawImage(sprite,x,y,width,height,null);
}
public boolean destroy(Block b){
if(b.y>=630){
b = null;
timer.cancel();
timer.purge();
return true;
} else { return false; }
}
public void update(int sec){
//if(getBounds().intersects(ShooterGame.ShooterGameClass.player.getBounds())){ System.out.println("Collision detected!"); }
timer = new Timer();
timer.schedule(new Move(), sec*1000);
destroy(this);
}
class Move extends TimerTask{
public void run(){
int keeper = 5;
if(keeper>0){
y+=5;
}
}
}
public Rectangle getBounds(){
return new Rectangle(x,y,width,height);
}
}
The main class(The game start)
ShooterGame.java:
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.*;
import java.net.URL;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.event.MouseEvent;
import game.input.InputHandler;
import game.player.Player;
import game.scenario.Block;
public class ShooterGame extends JFrame{
static int playerX=500;
static int playerY=520;
InputHandler input = new InputHandler(this);
public static Player player = new Player(playerX,playerY,50,50);
Block meteor = new Block(100,100,30,30);
public static void main(String[] args){
ShooterGame game = new ShooterGame();
game.run();
System.exit(0);
}
static int windowWidth = 1300;
static int windowHeight = 600;
static int fps = 30;
static BufferedImage backBuffer = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);
public void run(){
boolean running = true;
initialize();
while(running){
long time = System.currentTimeMillis();
update();
draw();
time = (1000 / fps) - (System.currentTimeMillis() - time);
if (time > 0) {
try{
Thread.sleep(time);
}
catch(Exception e){};
};
}
}
public void initialize(){
setTitle("--- Shooter Game ---");
setSize(windowWidth, windowHeight);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void update(){
player.update(input);
meteor.update(0);
}
public void draw(){
Graphics g = getGraphics();
Graphics bbg = backBuffer.getGraphics();
bbg.setColor(Color.BLACK);
bbg.fillRect(0, 0, windowWidth, windowHeight);
player.Draw(bbg);
meteor.Draw(bbg);
g.drawImage(backBuffer, 0, 0, this);
}
}
Commands:
compiling Player, Block and InputHandler(javac file.java)
then run the game with _java ShooterGame
You are probably trying to compile from inside the directory that the file is in, which is incorrectly setting the classpath.
cd game/player
javac Player.java
Instead of going into the subpackages, set the classpath explicitly and compile from the top level. I'm assuming that ShooterGame.java is in your game folder:
cd path/to/project/ShootGame
javac -cp . game/player/Player.java
... compile other classes
java -cp . game.ShooterGame

Java image wont move on mouse click?

I haven't looked at the code for this little game I made a while ago, and now all of the sudden the image won't move up when I click it?
I know the clicks are being called because the counter goes up. But the image won't move up. Any help is appreciated.
Batman class below
package Clicky;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Batman
{
private String batz = "batbomb.png";
private int x;
private int y;
private Image image;
private boolean visible;
public Batman()
{
ImageIcon ii = new ImageIcon(this.getClass().getResource(batz));
image = ii.getImage();
visible = true;
x = 145;
y = 620;
}
public int getX() { return x; }
public int getY() { return y; }
public Image getImage() { return image; }
public boolean isVisible()
{
return visible;
}
public void setVisible(boolean visible)
{
this.visible = visible;
}
public void mouseClicked(MouseEvent e)
{
int button = MouseEvent.BUTTON1;
if (button == MouseEvent.MOUSE_CLICKED)
{
y -= 1;
}
}
}
Where everything is drawn here
package Clicky;
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.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Clicky extends JPanel implements ActionListener
{
private Batman bat;
private Timer timer;
private int clicks = 0;
private boolean visible;
public Clicky() {
addMouseListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
timer = new Timer(5, this);
timer.start();
bat = new Batman();
}
public int getClickCount()
{
return clicks;
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g.setColor(Color.WHITE);
g2d.drawString("Clicks: " + getClickCount(), 10, 50);
g2d.drawRect(150, 70, 200, 600);
g2d.drawImage(bat.getImage(), bat.getX(), bat.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
repaint();
}
private class TAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
e.getClickCount();
clicks = clicks + 1;
}
}
}
Your Batman mouseClicked(MouseEvent e) method never gets called (if I'm wrong, please show me where). But even if it did, your MOUSE_CLICKED == BUTTON1 boolean check would always be false, since BUTTON1 and MOUSE_CLICKED are both constants and equal to different things, 1 and 500 respectively, and this will make sure that the if block never worked.

adding background pic to JFrame

I'm trying to follow this answer to add a background picture to a JFrame and I'm getting a weird error. While debugging my url is coming back null and I get a window that pops up saying "Class File Editor" source not found the source attachment does not contain the source for the file Launcher.class you can change the source attachment by clicking Chang Attached Source below. What does that mean?
here's the code that I have so far:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class DeluxKenoMainWindow extends JFrame
{
public DeluxKenoMainWindow()
{
initUI();
}
public final void initUI()
{
setLayout(null);
getContentPane().add(new BackgroundImage());
int xCoord = 10;
int yCoord = 10;
Button[] button = new Button[80];
for(int i = 0; i<80; i++)
{
String buttonName = "button" + i;
if(i % 10 == 0)
{
xCoord = 10;
yCoord +=40;
}
xCoord += 40;
if(i % 40 == 0)
yCoord += 8;
button[i] = new Button(buttonName, xCoord, yCoord, i+1);
getContentPane().add(button[i]);
}
setTitle("Delux Keno");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.setProperty("DEBUG_UI", "true");
DeluxKenoMainWindow ex = new DeluxKenoMainWindow();
ex.setVisible(true);
}
});
}
}
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.io.*;
public class Button extends JButton {
private String name;
private int xCoord;
private int yCoord;
private final int xSize = 40;
private final int ySize = 40;
private int buttonNumber;
private String picture;
public Button(String inName, int inXCoord, int inYCoord, int inButtonNumber)
{
xCoord = inXCoord;
yCoord = inYCoord;
buttonNumber = inButtonNumber;
picture = "graphics\\" + buttonNumber + "normal.png";
super.setName(name);
super.setIcon(new ImageIcon(picture));
super.setBounds(xCoord, yCoord, xSize, ySize);
}
}
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel{
private BufferedImage img;
private URL rUrl;
public BackgroundImage()
{
super();
try{
rUrl = getClass().getResource("formBackground.png");
img = ImageIO.read(rUrl);
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g)
{
//super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
any sugesstions will be appriciated!!
set classpath by #Gagandeep Bali
don't perform any FileIO in paintComponent, load this image one time as local variable, pass variable in paintComponent
for Bingo, Minesweaper to use JToggleButton instead of JButton
went at it a different way, using a JLabel. Here's my final code:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class DeluxKenoMainWindow extends JFrame
{
public DeluxKenoMainWindow()
{
initUI();
}
public final void initUI()
{
setLayout(null);
JLabel background = new JLabel(new ImageIcon ("graphics\\formBackground.png"));
background.setBounds(0,0,600,600);
//getContentPane().add(new BackgroundImage());
int xCoord = 85;
int yCoord = 84;
Button[] button = new Button[80];
for(int i = 0; i<80; i++)
{
String buttonName = "button" + i;
if(i % 10 == 0)
{
xCoord = 12;
yCoord +=44;
}
if(i % 40 == 0)
yCoord += 10;
button[i] = new Button(buttonName, xCoord, yCoord, i+1);
xCoord += 42;
getContentPane().add(button[i]);
}
add(background);
setTitle("Delux Keno");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
System.setProperty("DEBUG_UI", "true");
DeluxKenoMainWindow ex = new DeluxKenoMainWindow();
ex.setVisible(true);
}
});
}
}
another problem I found is that you need to use setBounds() for the JPanel for it to have any size. To do it the first way I tried this is the updated BackgroundImage class:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackgroundImage extends JPanel{
private BufferedImage img;
private URL rUrl;
public BackgroundImage()
{
super();
try{
rUrl = getClass().getResource("formBackground.png");
img = ImageIO.read(rUrl);
}
catch(IOException ex)
{
ex.printStackTrace();
}
super.setBounds(0,0,600,600);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}

Categories