0
\$\begingroup\$

I'm new to java and I want to know how to implement buttons for my menustate. Right now all I did is I made pictures of the buttons (play and exit) and just used g.drawImage to draw my Image to the game. Now I want to make those buttons useful. I also added mouse Input.

My code

MenuState

private static final int ButtonWidth = 256, ButtonHeight = 256;

  public MenuState(Handler handler){
    super(handler);
  }

  @Override
  public void tick() {
    if(handler.getMouseManager().isLeftPressed())
      State.setState(handler.getGame().gameState);
  }

  @Override
  public void render(Graphics g) {
    g.setColor(Color.RED);
    g.fillRect(handler.getMouseManager().getMouseX(), handler.getMouseManager().getMouseY(), 8, 8);
    g.drawImage(Assets.PlayButton, 500, 100, ButtonWidth, ButtonHeight, null );
    g.drawImage(Assets.ExitButton, 500, 400, ButtonWidth, ButtonHeight, null);
  }
}

MouseManager

  private boolean leftPressed;
  private int mouseX, mouseY;

  public MouseManager(){

  }

  //Getters

  public boolean isLeftPressed(){
    return leftPressed;
  }

  public int getMouseX(){
    return mouseX;
  }

  public int getMouseY(){
    return mouseY;
  }

  // Implemented methods

  @Override
  public void mousePressed(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1)
      leftPressed = true;

  }

  @Override
  public void mouseReleased(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1)
      leftPressed = false;
  }

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

  @Override
  public void mouseDragged(MouseEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void mouseClicked(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

  }
}

Handle(if needed)

public class Handler {

  private Game game;
  private World world;

  public Handler(Game game){
    this.game = game;
  }

  public GameCamera getGameCamera(){
    return game.getGameCamera();
  }

  public KeyManager getKeyManager(){
    return game.getKeyManager();
  }

  public MouseManager getMouseManager(){
    return game.getMouseManager();
  }

  public int getWidth(){
    return game.getWidth();
  }

  public int getHeight(){
    return game.getHeight();
  }

  public Game getGame() {
    return game;
  }

  public void setGame(Game game) {
    this.game = game;
  }

  public World getWorld() {
    return world;
  }

  public void setWorld(World world) {
    this.world = world;
  }
}

Game

  private Display display;
  private int width, height;
  public String title;

  private boolean running = false;
  private Thread thread;

  private BufferStrategy bs;
  private Graphics g;

  //States
  public State gameState;
  public MenuState menuState;

  //Input
  private KeyManager keyManager;
  private MouseManager mouseManager;

  //Camera
  private GameCamera gameCamera;

  //Handler
  private Handler handler;

  public Game(String title, int width, int height){
    this.width = width;
    this.height = height;
    this.title = title;
    keyManager = new KeyManager();
    mouseManager = new MouseManager();
  }

  private void init(){
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);
    Assets.init();

    handler = new Handler(this);
    gameCamera = new GameCamera(handler, 0, 0);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);
    State.setState(menuState);
  }

  private void tick(){
    keyManager.tick();

    if(State.getState() != null);
        State.getState().tick();
  }

  private void render(){
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null){
      display.getCanvas().createBufferStrategy(3);
      return;
    }
    g = bs.getDrawGraphics();
    //Clear Screen
    g.clearRect(0, 0, width, height);
    //Draw Here!

    if(State.getState() != null);
          State.getState().render(g);

    //End Drawing!
    bs.show();
    g.dispose();
  }

  public void run(){

    init();

    int fps = 1000;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();
    long timer = 0;
    int ticks = 0;

    while(running){
      now = System.nanoTime();
      delta += (now - lastTime) / timePerTick;
      timer += now - lastTime;
      lastTime = now;

      if(delta >=1){
        tick();
          render();
          ticks++;
          delta--;
      }
      if(timer >= 1000000000){
        System.out.println("Tick and Frames:" + ticks);
        ticks = 0;
        timer = 0;
      }
    }

    stop();

  }

  public KeyManager getKeyManager(){
    return keyManager;
  }

  public MouseManager getMouseManager(){
    return mouseManager;
  }

  public GameCamera getGameCamera(){
    return gameCamera;
  }

  public int getWidth(){
    return width;
  }

  public int getHeight(){
    return height;
  }

  public synchronized void start(){
    if(running)
      return;
    running = true;
    thread = new Thread(this);
    thread.start();
  }

  public synchronized void stop(){
    if(!running)
      return;
    running = false;
    try {
      thread.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
\$\endgroup\$
2
\$\begingroup\$

You can use the mouseClicked function and then check if the clicked coordinates are within the bounds of the button:

public void mouseClicked(MouseEvent e){
   if(button.x < e.getX() && buttonWidth + button.x > e.getX() && button.y < e.getY() && button.y + buttonHeight > e.getY(){
        //Button has been clicked
    }
}

In your case for the play button button.x would be 500 and button.y would be 100. Also please don't post all of the code, we only need relevant code...

This is how I did it (Don't change your code that does work for you as I made this in 5 minutes and what I made is probably not very optimized):

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Game implements MouseListener{

    public static void main(String[] args){
            new Game();
    }

    private JFrame frame;
    private Game(){
        init();
        loop();
    }

    private void init(){
        frame = new JFrame("TEST");
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.setSize(600, 400);
        frame.addMouseListener(this);
        running = true;
        frame.setVisible(true);
    }

    private boolean shouldClose = false;
    private boolean running;
    private final int buttonWidth = 100;
    private final int buttonHeight = 50;
    private void loop(){
        while(running){
            Graphics g = frame.getGraphics();
            g.drawRect(500, 100, buttonWidth, buttonHeight);
        }
        frame.setVisible(false);
    }

@Override
public void mouseClicked(MouseEvent e) {
    if(500 < e.getX() && buttonWidth + 500 > e.getX() && 100 < e.getY() && 100 + buttonHeight > e.getY()){
        System.out.println("BUTTON WAS PRESSED!");
        running = false;
    }
}

@Override
public void mousePressed(MouseEvent e) {

}

@Override
public void mouseReleased(MouseEvent e) {

}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {

}
}
\$\endgroup\$
10
  • \$\begingroup\$ thnx dude, it helped \$\endgroup\$ – SreeLegend Oct 23 '16 at 2:30
  • \$\begingroup\$ @SreeLegend Dont forget to mark this question as answered, so that it doesn't attract attention of people who still want to help you \$\endgroup\$ – Lucurious Oct 23 '16 at 5:48
  • \$\begingroup\$ when I typed 500 for Button.x and 100 for Button.y ,It didn't work. and when I typed Button.x and Buton.y(imported) it showed an error. \$\endgroup\$ – SreeLegend Oct 23 '16 at 13:41
  • \$\begingroup\$ and here is my mouseClicked code: \$\endgroup\$ – SreeLegend Oct 23 '16 at 13:41
  • \$\begingroup\$ @Override public void mouseClicked(MouseEvent e) { if(Button.x < e.getX() && MenuState.ButtonWidth + Button.x > e.getX() && Button.y < e.getY() && Button.y + MenuState.ButtonHeight > e.getY()){ //Button has been clicked } } \$\endgroup\$ – SreeLegend Oct 23 '16 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.