0

Como faço para atualizar o jTextArea? Tento atualizá-lo com o clique de um botão, mas não consigo. Quero ir adicionando novos textos junto com os anteriores, mas até então sem sucesso. Realizei a implementação no terminal (System.out) e funcionou normalmente, o problema está em fazer com que o texto apareça no jTextArea. O que fazer?

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                   
}
9
  • Seu códio nao e executável. Para que seja possível te ajudar, forneça um Exemplo Mínimo, Completo e Verificável, assim será possível executar o codigo e verificar o problema.
    – user28595
    30/04/2018 às 12:42
  • pt.stackoverflow.com/questions/41571/… - isto não ajuda?
    – White
    30/04/2018 às 13:03
  • Sem um Exemplo Mínimo, Completo e Verificável fica dificil ajudar, e mandando a gente visitar outro link tambem nao ajuda. Visite o link e tente fornecer um exemplo que seja possivel qualquer um executar, se nao fica complicado te ajudar.
    – user28595
    30/04/2018 às 13:05
  • 1
    Como vamos te ajudar se nem conseguimos executar o codigo?
    – user28595
    30/04/2018 às 13:11
  • 1
    O código ainda nao é executavel. Dica para criar um exemplo executavel: 1) crie um novo projeto e isole somente o codigo problematico, removendo dependencias; 2) teste o codigo para ver se ele está funcionando.
    – user28595
    30/04/2018 às 13:20

1 Resposta 1

0

Bom, realizei a programação do zero e descobri o problema sozinho. Espero que minha pergunta e resposta possam ajudar outros com dúvidas semelhantes. O problema encontra-se no seguinte trecho de código:

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

A grande questão é que ao criar o Tela t = new Tela() estou criando uma outra instancia para a criação de outra tela na interface. Por isso a correção foi a seguinte:

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

}

Foi uma questão de falha em POO. Agradeço a todos que tentaram me ajudar e espero ajudar outros com a mesma dúvida.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .