Search code examples
javaarraysswingjtextfield

JTextField set text output wrong


I'm trying to build a GUI for a random name generator I built, at present I'm trying to get it to print out the names when I press a button.

However instead of a list of names all I get is "[]". I don't know much about GUI programming so I'm not sure whats going wrong here.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.nio.file.*;
import java.util.*;


public class Applet1 extends javax.swing.JApplet {

public static List<String> list = new ArrayList<String>();

public static void init(String args[])throws IOException{

      List<String> prefix = Files.readAllLines(Paths.get("prefix.txt"));
      List<String> suffix = Files.readAllLines(Paths.get("suffix.txt"));
      Random randomizer = new Random();


      String prefix2 = prefix.get(randomizer.nextInt(prefix.size()));
      String suffix2 = suffix.get(randomizer.nextInt(suffix.size()));                         
      Random ran = new Random();
      int C = ran.nextInt(5);

        for(int A=0;A <= 5;A++){
            if( C == 0 )
                list.add(prefix2 + " ");                
            else if( C>0 && C<3 )
                list.add(prefix2 + suffix2+ " ");                   
            else if( C>2 && C<6 )
                list.add(prefix2 + " " + prefix2 + suffix2+ " ");}}


public void init() {
    /* 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(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Applet1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the applet */
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                initComponents();
            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/**
 * This method is called from within the init() method 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() {

    jComboBox1 = new javax.swing.JComboBox<>();
    jButton1 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();

    setMinimumSize(new java.awt.Dimension(498, 517));

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "5", "10", "15" }));

    jButton1.setText("Press");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel1.setText("Select number of names and press button to Generate");

    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(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(121, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton1)
                .addComponent(jComboBox1,     javax.swing.GroupLayout.PREFERRED_SIZE, 21,     javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(33, Short.MAX_VALUE))
    );
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText(list.toString());
}                                        


// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration



}

As far as I can tell either I've broken the code somewhere or TextField can't handle String Arrays.


Solution

  • This method is never called:

    public static void init(String args[])throws IOException{ 
    

    As a result, the list remains empty.

    Other tips/notes/questions:

    1. An applet's size is set in the HTML, so the setting of any size (minimum, size or maximum) should never be called in code.

      setMinimumSize(new java.awt.Dimension(498, 517));
      
    2. Why code an applet? If it is due to the teacher specifying it, please refer them to Why CS teachers should stop teaching Java applets.

    3. See Java Plugin support deprecated and Moving to a Plugin-Free Web.
    4. From the look of the GUI at the size of the text field, it seems it actually needs to be a multi-line text area (JTextArea).