How to update text in jTextArea?

0

How do I update the jTextArea ? I try to update it with the click of a button, but I can not. I want to add new texts along with the previous ones, but until then without success. I did the implementation on the terminal (System.out) and it worked normally, the problem is in making the text appear in jTextArea . What to do?

public class Tela extends javax.swing.JFrame {
    /**
     * Creates new form Tela
     */
    public Tela() {
        initComponents();
    }
    static int option;
    static int acao,cont=0;
    static String conteudo,str;

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        lblValor = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        text = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(1, 1, 1));
        setResizable(false);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/graphics-1658177_960_720.png"))); // NOI18N

        jLabel1.setForeground(new java.awt.Color(5, 0, 0));
        jLabel1.setText("O que deseja fazer(digite uma opção):)");
        jLabel1.setToolTipText("");

        lblValor.setForeground(new java.awt.Color(1, 1, 1));
        lblValor.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblValor.setToolTipText("");

        jButton2.setText("Confirmar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane2.setAutoscrolls(true);

        text.setEditable(false);
        text.setColumns(20);
        text.setRows(5);
        jScrollPane2.setViewportView(text);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 712, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(lblValor, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(95, 95, 95)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblValor, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))
                .addGap(0, 29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        option = Integer.parseInt(lblValor.getText());
        cont+=1;
        historia(option,cont);
    }                                        

    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(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
       /* Create and display the form */
       Tela t = new Tela();
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                t.setVisible(true);
                t.text.setText("Seja bem-vindo ao jogo que as suas decisões podem  "
                + "matar ou salvar alguém...\nSó depende de você! Boa sorte!"
             + "Você está pronto?\n 1 - SIM\n 2 - NÃO\n\n");   
            }
        });    
    }
    public static void historia(int decisao,int cont){
        Textos text = new Textos();
        Tela t = new Tela();
        if(cont == 1){
            switch(decisao){
                case 1:
                    str = "Você tomou essa decisão... A partir de agora tudo está por sua\n"
             + "conta em risco... Salve-se... A aventura começa agora...\n";
                    t.text.append(str);//não atualiza o texto
                    System.out.println(t.text.getText());
            }
        }
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField lblValor;
    private javax.swing.JTextArea text;
    // End of variables declaration                   
}
    
asked by anonymous 30.04.2018 / 14:09

1 answer

0

Well, I did the programming from scratch and discovered the problem myself. I hope my question and answer can help others with similar questions. The problem is in the following code snippet:

public static void historia(int decisao,int cont){
    Textos text = new Textos();
    Tela t = new Tela();
    if(cont == 1){
        switch(decisao){
            case 1:
                str = "Você tomou essa decisão... A partir de agora tudo está por sua\n"
         + "conta em risco... Salve-se... A aventura começa agora...\n";
                t.text.append(str);//não atualiza o texto
                System.out.println(t.text.getText());
        }
    }
}

The big question is that when I create Tela t = new Tela() I'm creating another instance for creating another screen in the interface. So the fix was as follows:

public static void historia(int decisao,int cont){
Textos text = new Textos();
if(cont == 1){
    switch(decisao){
        case 1:
            str = "Você tomou essa decisão...";
            this.text.append(str);//atualiza o texto
            System.out.println(t.text.getText());
    }
}

}

It was a matter of failure in OOP. Thanks to all who tried to help me and I hope to help others with the same doubt.

    
01.05.2018 / 13:01