繁体   English   中英

如何将actionEvents传递给另一个类?

[英]How do I pass actionEvents to another class?

基本上,我想在这里完成的是一个Gamebook模拟器应用程序,到目前为止,我已经使用NetBeans构建了所有JFrame,因为它具有友好的方法。

这是我的问题,这是我的“书”类,它讲述故事并为玩家提供他可能选择继续前进的可能选择。 它还会生成游戏主屏幕,并将所有值传递给它,例如jText(历史记录)和jLabels(例如玩家姓名,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()是一个jFrame类型的类,正在运行我在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);
            }
        });
    }

由于我的窗口是由NetBeans生成的,而button方法都是私有的,我无法更改,因此尝试捕获玩家按哪个jButton(游戏选择)时遇到了麻烦。 我需要能够确定从LivroTeste类内部按下了哪一个,因为它将控制游戏流程并根据玩家的选择刷新所有文本,历史记录和选择。 谁能指导我实现这一目标的最佳方法是什么? 提前致谢。

步骤1:修改LivroTeste ,使其实现ActionListener

步骤2:修改T_Jogo ,如下所示:

(a)在T_Jogo创建一个实例变量, T_Jogo所示:

  private LivroTeste livroTeste;

(b)修改构造函数T_Jogo(Jogador jogador)以接受另一个参数,以使其变为:

  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()));
}

步骤3:在LivroTeste.iniciarHistoria() ,创建T_Jogo的实例,如下所示:

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

步骤4:现在,在LivroTeste.actionPerformed()您将知道已按以下方式按下了哪一个:

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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM