在Java中按下按钮时更改精灵图像

时间:2014-12-18 00:28:40

标签: java

我一直在为学校开发Java游戏,但我遇到了一个问题。在创建我的菜单时(我现在就是这个)我尝试使用精灵创建一个按钮。

我现在就拥有它,以便当鼠标放在精灵上时,它会改变图像但我想在按下它时显示不同的精灵。然后当释放鼠标时,当鼠标悬停在图像上时,精灵将恢复为精灵。

游戏类:

import java.awt.Canvas;
import java.awt.Color;
//import java.awt.Color;
import java.awt.Dimension;
//import java.awt.Font;
//import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;

// This is the width, height, scale and title of the window.
public static int width = 1280 / 4;
public static int height = 720 / 4;
public static int scale = 4;
public static String title = "Ultimate Defender 2";

// Mouse object created.
private Mouse mouse = new Mouse();

// Creates all the SpriteSheet objects.
public SpriteSheet menubackgroundimage = new SpriteSheet();
public SpriteSheet menutitle = new SpriteSheet();
public SpriteSheet playbutton[] = new SpriteSheet[3];
public SpriteSheet continuebutton[] = new SpriteSheet[3];
public SpriteSheet scoresbutton[] = new SpriteSheet[3];
public SpriteSheet settingsbutton[] = new SpriteSheet[3];
public SpriteSheet exitbutton[] = new SpriteSheet[3];
public SpriteSheet backgroundimage = new SpriteSheet();
public SpriteSheet mobs = new SpriteSheet();
public SpriteSheet turret = new SpriteSheet();

// Creates the thread, frame and graphics objects.
private Thread thread;
private JFrame frame;
private Graphics2D graphics;

// Running variable is created to see if the game is running or not.
// Is used with the thread object.
private boolean running = false;

// Creates a BufferedImage object.
//  private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// The constructor is initialized at launch of the game.
public Game() {
    Dimension size = new Dimension(width * scale, height * scale);
    setPreferredSize(size);

    frame = new JFrame();

    addMouseMotionListener(mouse);
    addMouseListener(mouse);
}

// Starts the thread.
public synchronized void start() {
    running = true;
    thread = new Thread(this, "Display");
    thread.start();
}

// Stops the thread.
public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
}

// Loads the UPS and FPS and also initializes certain stuff.
public void run() {
    init();
    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;
    int frames = 0;
    int updates = 0;
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1) {
            update();
            updates++;
            delta--;
        }
        render();
        frames++;

        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            frame.setTitle(title + "  |  " + updates + " UPS, " + frames + " FPS");
            updates = 0;
            frames = 0;
        }
    }
    stop();
}

// Initializes objects such as images and other stuff.
private void init() {
    initializeSprites();
}

// Initializes all of the sprite images.
private void initializeSprites() {
    menubackgroundimage.loadSpriteSheet("images/Menu-Background.png");
    menutitle.loadSpriteSheet("images/Ultimate-Defender-2.png");
    for (int i = 0; i < 3; i++) {
        playbutton[i] = new SpriteSheet();
        playbutton[i].loadSpriteSheet("images/Start" + (i + 1) + ".png");

        continuebutton[i] = new SpriteSheet();
        continuebutton[i].loadSpriteSheet("images/Continue" + (i + 1) + ".png");

        scoresbutton[i] = new SpriteSheet();
        scoresbutton[i].loadSpriteSheet("images/Scores" + (i + 1) + ".png");

        settingsbutton[i] = new SpriteSheet();
        settingsbutton[i].loadSpriteSheet("images/Settings" + (i + 1) + ".png");

        exitbutton[i] = new SpriteSheet();
        exitbutton[i].loadSpriteSheet("images/Exit" + (i + 1) + ".png");
    }
    // backgroundimage.loadSpriteSheet("images/grass.png");
    // mobs.loadSpriteSheet("images/.png");
    // turret.loadSpriteSheet("images/.png");
}

// Updates game objects.
public void update() {

}

// This renders all images and other stuff.
public void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    graphics = (Graphics2D) bs.getDrawGraphics();
    draw();
    graphics.dispose();
    bs.show();
}

// Calls gameState which decides what to draw.
private void draw() {
    gameState();
}

// Calls all methods that will be needed for creating the images for the game depending on what state it's in.
private void gameState() {
    // Menu
    drawMenuBackground();
    drawMenuTitle();
    drawPlayButton();
    drawContinueButton();
    drawScoresButton();
    drawSettingsButton();
    drawExitButton();
}

// Draws the menu background.
private void drawMenuBackground() {
    BufferedImage MenuBackground = menubackgroundimage.getSprite(0, 0, 900, 540);
    graphics.drawImage(MenuBackground, 0, 0, 1280, 720, null);
}

// Draws the menu title.
private void drawMenuTitle() {
    BufferedImage MenuTitle = menutitle.getSprite(0, 0, 1043, 160);
    graphics.drawImage(MenuTitle, ((getWidth() / 2) - (1043 / 2)), 65, 1043, 160, null);
}

// Draws the play button.
public void drawPlayButton() {
    Point2D mouseCoord = new Point2D.Double(mouse.getMouseX(), mouse.getMouseY());
    Rectangle2D playButton = new Rectangle2D.Double(((getWidth() / 2) - (178 / 2)), 275, 178, 66);

        BufferedImage PlayButton[] = new BufferedImage[3];
        for (int i = 0; i < 3; i++) {
        PlayButton[i] = playbutton[i].getSprite(0, 0, 178, 66);
    }

        if (playButton.contains(mouseCoord)) {
        if (mouse.isMousePressed()) {
            graphics.drawImage(PlayButton[2], ((getWidth() / 2) - (178 / 2)), 275, 178, 66, null);

                if (mouse.isMouseReleased()) {
                graphics.drawImage(PlayButton[1], ((getWidth() / 2) - (178 / 2)), 275, 178, 66, null);
            }
        }
        else {
            graphics.drawImage(PlayButton[1], ((getWidth() / 2) - (178 / 2)), 275, 178, 66, null);
        }
    }
    else {
        graphics.drawImage(PlayButton[0], ((getWidth() / 2) - (178 / 2)), 275, 178, 66, null);
    }
}

// Draws the continue button.
public void drawContinueButton() {
    Point2D mouseCoord = new Point2D.Double(mouse.getMouseX(), mouse.getMouseY());
    Rectangle2D continueButton = new Rectangle2D.Double(((getWidth() / 2) - (241 / 2)), 355, 241, 69);

    BufferedImage ContinueButton[] = new BufferedImage[3];
    for (int i = 0; i < 3; i++) {
        ContinueButton[i] = continuebutton[i].getSprite(0, 0, 241, 69);
    }

    if (continueButton.contains(mouseCoord)) {
        graphics.drawImage(ContinueButton[1], ((getWidth() / 2) - (241 / 2)), 355, 241, 69, null);
    }
    else {
        graphics.drawImage(ContinueButton[0], ((getWidth() / 2) - (241 / 2)), 355, 241, 69, null);
    }
}

// Draws the scores button.
public void drawScoresButton() {
    Point2D mouseCoord = new Point2D.Double(mouse.getMouseX(), mouse.getMouseY());
    Rectangle2D scoresButton = new Rectangle2D.Double(((getWidth() / 2) - (208 / 2)), 435, 208, 66);

    BufferedImage ScoresButton[] = new BufferedImage[3];
    for (int i = 0; i < 3; i++) {
        ScoresButton[i] = scoresbutton[i].getSprite(0, 0, 208, 66);
    }

    if (scoresButton.contains(mouseCoord)) {
        graphics.drawImage(ScoresButton[1], ((getWidth() / 2) - (208 / 2)), 435, 208, 66, null);
    }
    else {
        graphics.drawImage(ScoresButton[0], ((getWidth() / 2) - (208 / 2)), 435, 208, 66, null);
    }
}

// Draws the settings button.
public void drawSettingsButton() {
    Point2D mouseCoord = new Point2D.Double(mouse.getMouseX(), mouse.getMouseY());
    Rectangle2D settingsButton = new Rectangle2D.Double(((getWidth() / 2) - (238 / 2)), 515, 238, 76);

    BufferedImage SettingsButton[] = new BufferedImage[3];
    for (int i = 0; i < 3; i++) {
        SettingsButton[i] = settingsbutton[i].getSprite(0, 0, 238, 76);
    }

    if (settingsButton.contains(mouseCoord)) {
        graphics.drawImage(SettingsButton[1], ((getWidth() / 2) - (238 / 2)), 515, 238, 76, null);
    }
    else {
        graphics.drawImage(SettingsButton[0], ((getWidth() / 2) - (238 / 2)), 515, 238, 76, null);
    }
}

// Draws the exit button.
public void drawExitButton() {
    Point2D mouseCoord = new Point2D.Double(mouse.getMouseX(), mouse.getMouseY());
    Rectangle2D exitButton = new Rectangle2D.Double(((getWidth() / 2) - (148 / 2)), 595, 148, 69);

    BufferedImage ExitButton[] = new BufferedImage[3];
    for (int i = 0; i < 3; i++) {
        ExitButton[i] = exitbutton[i].getSprite(0, 0, 148, 69);
    }

    if (exitButton.contains(mouseCoord)) {
        graphics.drawImage(ExitButton[1], ((getWidth() / 2) - (148 / 2)), 595, 148, 69, null);

        if (mouse.isMouseClicked()) {
            System.exit(JFrame.EXIT_ON_CLOSE);
            stop();
        }
    }
    else {
        graphics.drawImage(ExitButton[0], ((getWidth() / 2) - (148 / 2)), 595, 148, 69, null);
    }
}

// Actually starts the game.
public static void main(String[] args) {
    Game game = new Game();
    game.frame.setResizable(false);
    game.frame.setTitle(Game.title);
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);

    game.start();
}

}

SpriteSheet类:

import java.awt.image.*;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteSheet {

public BufferedImage spriteSheet;

public void loadSpriteSheet(String fileName) {
    try {
    //  BufferedImage sheet = ImageIO.read(new File(fileName));
        BufferedImage sheet = ImageIO.read(ResourceLoader.load(fileName));
        spriteSheet = sheet;
    } catch (IOException e) {System.out.println("No Image");}
}

public BufferedImage getSprite(int x, int y, int w, int h) {
    BufferedImage sprite = spriteSheet.getSubimage(x, y, w, h);
    return sprite;
}

}

ResourceLoader类:

import java.io.*;

public class ResourceLoader {

final static InputStream load(String path1){
    InputStream input = ResourceLoader.class.getResourceAsStream(path1);
    if(input == null){
        input = ResourceLoader.class.getResourceAsStream("/" + path1);
    }
    return input;
}

}

鼠标类:

import java.awt.event.*;

public class Mouse implements MouseMotionListener,MouseListener{

private int mouseX, mouseY;
private boolean mouseClicked, mousePressed, mouseReleased;

public void mouseClicked(MouseEvent e) {
    mouseClicked = true;
}

public void mouseEntered(MouseEvent e) {

}

public void mouseExited(MouseEvent e) {

}

public void mousePressed(MouseEvent e) {
    mousePressed = true;
}

public void mouseReleased(MouseEvent e) {
    mouseReleased = true;
}

public void mouseDragged(MouseEvent arg0) {

}

public void mouseMoved(MouseEvent e) {
    mouseX = e.getX();
    mouseY=  e.getY();
}

public int getMouseX() {
    return mouseX;
}

public void setMouseX(int mouseX) {
    this.mouseX = mouseX;
}

public int getMouseY() {
    return mouseY;
}

public void setMouseY(int mouseY) {
    this.mouseY = mouseY;
}

public boolean isMouseClicked() {
    return mouseClicked;
}

public void setMouseClicked(boolean mouseClicked) {
    this.mouseClicked = mouseClicked;
}

public boolean isMousePressed() {
    return mousePressed;
}

public void setMousePressed(boolean mousePressed) {
    this.mousePressed = mousePressed;
}

public boolean isMouseReleased() {
    return mouseReleased;
}

public void setMouseReleased(boolean mouseReleased) {
    this.mouseReleased = mouseReleased;
}

}

0 个答案:

没有答案