0

Basically what I am trying to accomplish here is a Gamebook simulator application, so far I've been building all my JFrames using NetBeans, since it has a noob friendly approach.

Here is my problem, this is my "book" class which tells the story and presents the player with the possible options he may choose to progress. It also generates the main game screen and passes to it all values, like jText (history) and jLabels(such as player name, life...).

package estrutura;

public class LivroTeste extends Livro {

        public LivroTeste(Jogador jogador) {
            super(null, null);
        }

    public void iniciarHistoria(Jogador jogador) {

                T_Jogo jogo = new T_Jogo(jogador);
                jogo.setVisible(true);

                System.out.println("NOME DO PUTO: " + jogador.getNome());

        Encontro i = new Encontro("Você está no fluxo e avista o José no grau, "
                + "você sabe o que ele quer?");
                jogo.printEncontro(i.getDescricao());

        i.addEscolhas("Ele quer pau, pau, pau, pau, ele quer pau...");
        i.addEscolhas("O Zé quer upar!");
                i.addEscolhas("Ele quer Shirlar!");
                i.addEscolhas("Nenhuma das anteriores.");

                jogo.add0(i.getEscolhas().get(0));
                jogo.add1(i.getEscolhas().get(1));
                jogo.add2(i.getEscolhas().get(2));
                jogo.add3(i.getEscolhas().get(3));

                System.out.println("CHEGOU AQUI!");

    }

    public void floresta1(Jogador jogador) {
        Encontro f1 = new Encontro(jogador.getNome() + " segue pela floresta...");
    }

    public void rio1(Jogador jogador) {
        Encontro r1 = new Encontro("Você avista o rio e começa a caminhar pela margem...");
    }
}

T_Jogo() is a jFrame type class, being jogo my main screen initialized inside LivroJogo:

package estrutura;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

public class T_Jogo extends javax.swing.JFrame implements ActionListener {

    /**
     * Creates new form T_Jogo
     */
    public T_Jogo() {
        initComponents();

        this.setResizable(false);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
    }

    public T_Jogo(Jogador jogador) {
        initComponents();

        //Centraliza janela e desabilita botão maximizar
        this.setResizable(false);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

        jTextArea1.setEditable(false);
        jTextArea1.setLineWrap(true);

        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
        jButton3.addActionListener(this);
        jButton4.addActionListener(this);

        jLabel1.setText(jogador.getNome());
        jLabel5.setText(Integer.toString(jogador.getVida()));
        jLabel6.setText(Integer.toString(jogador.getAtaque()));
        jLabel7.setText(Integer.toString(jogador.getPericia()));
    }
    .
    .
    .
     public void actionPerformed(ActionEvent e) {
        if(e.getSource() == jButton1) 
            JOptionPane.showMessageDialog(this, "Botão 1");

        else if(e.getSource() == jButton2)
            JOptionPane.showMessageDialog(this, "Botão 2");

        else if(e.getSource() == jButton3)
            JOptionPane.showMessageDialog(this, "Botão 3");

        else if(e.getSource() == jButton4)
            JOptionPane.showMessageDialog(this, "Botão 4");
    }
    public void printEncontro(String texto) {
        jTextArea1.setText(texto);
    } 
    public void add0(String texto) {
        opcao1.setText(texto);
    }
    public void add1(String texto) {
        opcao2.setText(texto);
    } 
    public void add2(String texto) {
        opcao3.setText(texto);
    }
    public void add3(String texto) {
        opcao4.setText(texto);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(T_Jogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(T_Jogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(T_Jogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(T_Jogo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new T_Jogo().setVisible(true);
            }
        });
    }

I am facing troubles trying to capture which jButton (the game choices) the player presses, since my windows have been generated by NetBeans and the buttons methods are all private, which I can't change. I need to be able to determine wich one has been pressed from inside LivroTeste class, since it will control the game flow and refresh all the text, history and choices, based on what the player have choose. Could anyone please guide me in what would be the best way of achieving this? Thanks in advance.

Lazzo
  • 23
  • 6
  • How do you use the class `LivroTeste` from your class `T_Jogo`? – Sanjeev Saha Jul 03 '16 at 16:14
  • It's actually the other way around, T_Jogo is used inside LivroTeste. It's a bit complicated and not posted here, but the game flow starts in a Engine class with a static main(), inside that I initialized the first jFrame, something like "T_Opening", inside T_Opening, when the user click "Start", this jButton calls for another jFrame, which goes has another jButton that leads to player choosing which "book" he wants to play. At this point, it calls LivroTeste(), which is the only book avaible so far (sorry if couldn't make it any clear). – Lazzo Jul 03 '16 at 16:26
  • So `T_Jogo` is not the entry point of your application. I thought so because of the `main` method. – Sanjeev Saha Jul 03 '16 at 16:38
  • *"I've been building all my JFrames.."* See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) *"..using NetBeans, since it has a noob friendly approach."* A powerful IDE is a boon to experienced programmers, and a bane to newbies, because.. *"since my windows have been generated by NetBeans and the buttons methods are all private"* the newbie is the 'dog' in the saying 'the tail wagging the dog'.. – Andrew Thompson Jul 03 '16 at 17:00

1 Answers1

0

Step 1: Modify LivroTeste so that it implements ActionListener

Step 2: Modify T_Jogo as follows:

(a) Create an instance variable in T_Jogo like:

  private LivroTeste livroTeste;

(b) Modify the constructor T_Jogo(Jogador jogador) to accept one more parameter so that it becomes:

  public T_Jogo(Jogador jogador, LivroTeste livroTeste) {
    this.livroTeste = livroTeste;
    initComponents();

    //Centraliza janela e desabilita botão maximizar
    this.setResizable(false);
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

    jTextArea1.setEditable(false);
    jTextArea1.setLineWrap(true);

    jButton1.setActionCommand("jButton1");
    jButton1.addActionListener(livroTeste);

    jButton2.setActionCommand("jButton2");
    jButton2.addActionListener(livroTeste);

    jButton3.setActionCommand("jButton3");
    jButton3.addActionListener(livroTeste);

    jButton4.setActionCommand("jButton4");
    jButton4.addActionListener(livroTeste); 

    jLabel1.setText(jogador.getNome());
    jLabel5.setText(Integer.toString(jogador.getVida()));
    jLabel6.setText(Integer.toString(jogador.getAtaque()));
    jLabel7.setText(Integer.toString(jogador.getPericia()));
}

Step 3: In LivroTeste.iniciarHistoria(), create the instance of T_Jogo as follows:

T_Jogo jogo = new T_Jogo(jogador, this);   
jogo.setVisible(true);

Step 4: Now, in LivroTeste.actionPerformed() you will know which one has been pressed in following manner:

 public void actionPerformed(ActionEvent e) {
    String str = e.getActionCommand();
    if(str.equals("jButton1")){
       JOptionPane.showMessageDialog(null, "Botão 1");
    }
  } 

Hope, this helps.

Sanjeev Saha
  • 2,632
  • 1
  • 12
  • 19
  • Thank you very much for spending your time trying to help me. Made all the changes, still it doesn't seem to work properly. I don't get any kind of errors, but neither I know which button is being pressed, JPaneOption simply doesn't show at all. I tried the following with all the 4 buttons: case "jButton1": JOptionPane.showMessageDialog(null, "Botão 1"); System.out.println(str); break; Any thoughts?? – Lazzo Jul 03 '16 at 18:40
  • Can you pass one more parameter in the constructor of `public T_Jogo(Jogador jogador)` so that it becomes `public T_Jogo(Jogador jogador, LivroTeste livroTeste){ this.livroTeste = livroTeste; initComponents(); // more code follows` and create object in `LivroTeste` by `T_Jogo jogo = new T_Jogo(jogador, this);`. Try once more. It should work because the action listener for your buttons are now `LivroTeste`. So its `actionPerformed()` must get invoked when buttons are clicked. – Sanjeev Saha Jul 03 '16 at 19:16
  • Thank you for the fast reply, now it is working just as intended.I just dunno why it wasn't before, since T_Jogo() was receiving LivroTeste() by the setter. Anyway, thank you for all your help! – Lazzo Jul 03 '16 at 19:23
  • Hi @Lazzo could you please take a look at my edited answer? I have modified it the way it has worked for you. Would you mind accepting the answer by click the check mark (✓) button on the left of the answer so that readers may know how to solve similar problems? – Sanjeev Saha Jul 04 '16 at 02:10