更改textarea的文本

时间:2014-06-28 20:25:48

标签: java swing jtextarea settext

我有一个类,它创建一个包含textarea和其他元素的图形界面。为了创建GUI,我使用了NetBeans,因此存在一些不可编辑的代码。 我的问题是我无法更改textarea中的文本。我尝试使用 setText() append(),但textarea不会改变。问题在哪里?

  public class Cifra extends javax.swing.JFrame {

     /** Creates new form Cifra */
     public Cifra() {
        initComponents();
     }

     /** This method is called from within the constructor to
      * initialize the form.
      * WARNING: Do NOT modify this code. The content of this method is
      * always regenerated by the Form Editor.
      */
     @SuppressWarnings("unchecked")
     // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
     private void initComponents() {

        comboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        chiaveField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        antMexCif = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        antMex = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        logoutButton = new javax.swing.JButton();
        inviaPropostaButton = new javax.swing.JButton();
        indietroButton = new javax.swing.JButton();
        cifra = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cifra");

        comboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Scegli cifratura...", "Cesare", "Pseudocasuale", "Chiave" }));
        comboBox.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
              comboBoxActionPerformed(evt);
           }
        });

        jLabel1.setText("Inserisci una chiave:");

        chiaveField.setColumns(20);

        antMexCif.setEditable(false);
        antMexCif.setColumns(20);
        antMexCif.setRows(5);
        jScrollPane1.setViewportView(antMexCif);

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

        jLabel2.setText("Anteprima messaggio originale:");

        jLabel3.setText("Anteprima messaggio cifrato:");

        logoutButton.setText("Logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
              logoutButtonActionPerformed(evt);
           }
        });

        inviaPropostaButton.setText("Invia proposta");

        indietroButton.setText("Indietro");
        indietroButton.setToolTipText("");
        indietroButton.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
              indietroButtonActionPerformed(evt);
           }
        });

        cifra.setText("Cifra");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(layout.createSequentialGroup()
              .addGap(28, 28, 28)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addComponent(comboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                 .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                       .addGroup(layout.createSequentialGroup()
                          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                             .addComponent(jLabel2)
                             .addComponent(logoutButton))
                          .addGap(168, 168, 168))
                       .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                          .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                       .addGroup(layout.createSequentialGroup()
                          .addComponent(indietroButton)
                          .addGap(40, 40, 40)
                          .addComponent(cifra)
                          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                          .addComponent(inviaPropostaButton))
                       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                             .addComponent(jLabel3)
                             .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE))
                          .addGroup(layout.createSequentialGroup()
                             .addComponent(jLabel1)
                             .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                             .addComponent(chiaveField, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))))))
              .addGap(31, 69, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(layout.createSequentialGroup()
              .addContainerGap()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                 .addComponent(comboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                 .addComponent(jLabel1)
                 .addComponent(chiaveField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addGroup(layout.createSequentialGroup()
                    .addGap(9, 9, 9)
                    .addComponent(jLabel2))
                 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel3)))
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                 .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                 .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                       .addComponent(inviaPropostaButton)
                       .addComponent(indietroButton)
                       .addComponent(cifra)))
                 .addGroup(layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(logoutButton)))
              .addContainerGap(16, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(741, 389));
        setLocationRelativeTo(null);
     }// </editor-fold>                                                                  

     /**
      * @param args the command line arguments
      */
     public static void start() {
        /* 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(Cifra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
           java.util.logging.Logger.getLogger(Cifra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
           java.util.logging.Logger.getLogger(Cifra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
           java.util.logging.Logger.getLogger(Cifra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
          //</editor-fold>
           antMex = new javax.swing.JTextArea(DBManager.messaggio.getTesto() + newline);

           antMex.append("hello world" + newline);
           antMex.setText("hello world");

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

     private final static String newline = "\n";
     // Variables declaration - do not modify                     
     public static javax.swing.JTextArea antMex;
     private javax.swing.JTextArea antMexCif;
     private javax.swing.JTextField chiaveField;
     public static javax.swing.JButton cifra;
     private javax.swing.JComboBox comboBox;
     private javax.swing.JButton indietroButton;
     private javax.swing.JButton inviaPropostaButton;
     private javax.swing.JLabel jLabel1;
     private javax.swing.JLabel jLabel2;
     private javax.swing.JLabel jLabel3;
     private javax.swing.JScrollPane jScrollPane1;
     private javax.swing.JScrollPane jScrollPane2;
     private javax.swing.JButton logoutButton;
     // End of variables declaration                   
  }

谢谢!

2 个答案:

答案 0 :(得分:3)

您的问题的关键在于您需要了解对象和变量之间的区别。

您正在创建一个新的JTextArea对象并将其放入antMex变量,然后设置该对象的文本:

// ******* here *******
antMex = new javax.swing.JTextArea(DBManager.messaggio.getTesto() + newline);

antMex.append("hello world" + newline);
antMex.setText("hello world");

理解这对创建的原始JTextArea对象完全没有影响,分配给antMex,并在创建和分配新对象之前添加到GUI中。

解决方案:不要创建新对象,而是继续调用原始引用上的方法。

// commenting out the line that creates the new JTextArea
// antMex = new javax.swing.JTextArea(DBManager.messaggio.getTesto() + newline);

antMex.append("hello world" + newline);
antMex.setText("hello world");

更好的解决方案:避免使用GUI代码生成器,直到您有更多的Swing体验。相信我,你将通过Swing和一般Java教程学到很多东西。


修改
Rod Algonquin非常重视我的建议是在你的对象创建之前做出的。相反,考虑给出Cifra公共方法,如:

public void setAntMexText(String text) {
  antMex.setText(text);
}

public void appendAntMexText(String text) {
  antMex.append(text);
}

并像这样称呼他们:

  java.awt.EventQueue.invokeLater(new Runnable() {
     public void run() {
        Cifra cifra = new Cifra();
        cifra.setVisible(true);
        cifra.setAntMexText("Hello World!" + NEW_LINE); // NEW_LINE should be all caps
        cifra.appendAntMexText("Next Line");
     }
  });

答案 1 :(得分:1)

       antMex.append("hello world" + newline);
       antMex.setText("hello world");

initComponents()语句之后,该代码应该在您的类的构造函数中。

也就是说,在创建变量之前,你无法引用变量。