How to assign action to Image or Button

Asked

Viewed 461 times

-1

I am developing the home page of a simple game, what I wish is to add a button on the screen where when clicking the game start, follows below my code of how I am mounting the menu and bringing the background, the code brings the image I put as the button, but I’m failing to assign the click action to the same, I don’t know what would be the best way to do it, I accept ideas.

public Menu(){

        setFocusable(true);
        setDoubleBuffered(true);

        ImageIcon referencia = new ImageIcon("res\\images\\fundo.png");

        fundo = referencia.getImage();
        emJogo = true; //iniciar jogo
        timer = new Timer(5, this);
        timer.start();

        ImageIcon referencia2 = new ImageIcon("res\\images\\btn1.png");
        jogar = referencia2.getImage();

    }

    public void paint(Graphics g){  

        Graphics2D graficos = (Graphics2D) g;
        graficos.drawImage(fundo, 0, 0, null);
        graficos.drawImage(jogar, 0, 0, null);

        g.dispose();

    }
  • Jbutton ? If it is, just call the actionperformed method and insert the action into it. See an example http://answall.com/questions/12471/calculator-com-interface-gr%C3%A1fica-java/12476#12476

  • Try to play the image on one JLabel, just make sure she gets the right sizes and stuff. JLabel lb = new JLabel(referencia2);. If it works, I’ll give you an answer.

1 answer

0

Just register an event for your button as follows the example below and be happy. Most components have the "addActionListener" method to link the click event.

// Adicionando um evento action ao botão
botao.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {

            // Aqui você escreve qual será a ação do botão ao ser clicado!
            botao.setText(campo.getText());
        }
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.