0

I've made an application in java using NetBeans IDE and I'm having a problem. It doesn't read the array elements. Here's the code:

private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
       String[] toppings = new String[20];
       toppings[0] = "";
       toppings[1] = "";
       toppings[2] = "";
       toppings[3] = "";

       int size = toppings.length;
       for (int i=0; i<size; i++){
          toppings[i]=textbox.getText();
          label1.setText(toppings[0]); 
          label2.setText(toppings[1]);
          label3.setText(toppings[2]);
          label4.setText(toppings[3]);
       }
}

I want to put then each element of the array on the labels(label1,label2,label3,label4) each time I press the button and add a new value for a new element in the vector.

At this time, when I type the value of the first element it sets the value to all labels.

Does anybody have an idea please?

2
  • You're confusing vector with array. Commented Mar 29, 2013 at 17:50
  • This could also create problem int size = toppings.length; as it will give you 20. Commented Mar 29, 2013 at 17:51

2 Answers 2

2

You should create array of JLabel and then fill up the text on them in for loop:
enter image description here

    private javax.swing.JLabel label[];
   //write these lines within constructor or wherever you are creating your GUI

   label = new  javax.swing.JLabel[4];//
   for (int i = 0 ; i < label.length ;i++)
   label[i] = new javax.swing.jLabel();

Then change the buton1ActionPerformed

private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {
   String[] toppings = new String[20];
   toppings[0] = "";
   toppings[1] = "";
   toppings[2] = "";
   toppings[3] = "";

   int size = toppings.length;
   for (int i=0; i<size; i++){
      toppings[i]=textbox.getText();
      if (i < 4)
      label[i].setText(toppings[i]); 
   }
}

EDIT
Here I have put the updated version of your code. Just run it and tell me if it fulfills what you looking for:

public class fereastra extends javax.swing.JFrame {

    /**
     * Creates new form fereastra
     */
    public fereastra() {
        initComponents();
        buttonGroup1.add(singleplayer);
        buttonGroup1.add(twoplayers);
        buttonGroup1.add(threeplayers);
        buttonGroup1.add(fourplayers);
        casutatext.setVisible(true);
        panel.setVisible(true);
        text.setText("Wellcome! Please choose the number of players!");


    }

    /**
     * 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() {
        label = new  javax.swing.JLabel[4];//
        for (int i = 0 ; i < label.length ;i++)
        {label[i] = new javax.swing.JLabel();}

        buttonGroup1 = new javax.swing.ButtonGroup();
        casutatext = new javax.swing.JTextField();
        text = new javax.swing.JLabel();
        buton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        panel = new javax.swing.JPanel();
        fourplayers = new javax.swing.JRadioButton();
        twoplayers = new javax.swing.JRadioButton();
        threeplayers = new javax.swing.JRadioButton();
        singleplayer = new javax.swing.JRadioButton();
        test = new javax.swing.JLabel();
        test2 = new javax.swing.JLabel();
        test3 = new javax.swing.JLabel();
        test4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        casutatext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                casutatextActionPerformed(evt);
            }
        });

        text.setText("Text");

        buton1.setText("OK");
        buton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Cancel");

        fourplayers.setText("4 players");
        fourplayers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fourplayersActionPerformed(evt);
            }
        });

        twoplayers.setText("2 players");
        twoplayers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                twoplayersActionPerformed(evt);
            }
        });

        threeplayers.setText("3 players");
        threeplayers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                threeplayersActionPerformed(evt);
            }
        });

        singleplayer.setText("Single player");
        singleplayer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                singleplayerActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(singleplayer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(twoplayers)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(threeplayers)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fourplayers)
                .addContainerGap())
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(singleplayer)
                    .addComponent(twoplayers)
                    .addComponent(threeplayers)
                    .addComponent(fourplayers))
                .addContainerGap())
        );

        test.setText("test");

        test2.setText("jLabel1");

        test3.setText("jLabel2");

        test4.setText("jLabel3");

        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()
                        .addGap(127, 127, 127)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(casutatext, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(158, 158, 158)
                        .addComponent(label[0])
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(buton1)
                                .addGap(35, 35, 35)
                                .addComponent(jButton3))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(label[1])
                                .addGap(32, 32, 32)
                                .addComponent(label[2])
                                .addGap(31, 31, 31)
                                .addComponent(label[3])))))
                .addGap(93, 93, 93))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addComponent(text)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(casutatext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buton1)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label[0])
                    .addComponent(label[1])
                    .addComponent(label[2])
                    .addComponent(label[3]))
                .addGap(51, 51, 51))
        );

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

    private void casutatextActionPerformed(java.awt.event.ActionEvent evt) {                                          

    }                                          

    private void buton1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
       String[] toppings = new String[20];
   toppings[0] = "";
   toppings[1] = "";
   toppings[2] = "";
   toppings[3] = "";

   int size = toppings.length;
   for (int i=0; i<size; i++){
      toppings[i]=casutatext.getText();
      if (i < 4)
      {label[i].setText(toppings[i]);
      }
   }
    }                                      

    private void singleplayerActionPerformed(java.awt.event.ActionEvent evt) {                                            
        numarjucatori=1;
    }                                            

    private void twoplayersActionPerformed(java.awt.event.ActionEvent evt) {                                          
        numarjucatori=2;
    }                                          

    private void threeplayersActionPerformed(java.awt.event.ActionEvent evt) {                                            
        numarjucatori=3;
    }                                            

    private void fourplayersActionPerformed(java.awt.event.ActionEvent evt) {                                            
        numarjucatori=4;
    }                                          

    /**
     * @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(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(fereastra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(fereastra.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 fereastra().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton buton1;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField casutatext;
    private javax.swing.JRadioButton fourplayers;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel panel;
    private javax.swing.JRadioButton singleplayer;
    private javax.swing.JLabel test;
    private javax.swing.JLabel test2;
    private javax.swing.JLabel test3;
    private javax.swing.JLabel test4;
    private javax.swing.JLabel text;
    private javax.swing.JRadioButton threeplayers;
    private javax.swing.JRadioButton twoplayers;
    // End of variables declaration
    public int numarjucatori;
    public String p1="", p2="", p3="", p4="";
    private javax.swing.JLabel label[];
}
Sign up to request clarification or add additional context in comments.

15 Comments

the label you wrote (label) isn't in the interface, so it does not appear. can you tell me how to make it appear?
@DanielPatilea If you put your all code for this class , I would be able to assist you much better. By the way..Is label1,label2... inherited from an interface??
@DanielPatilea Put your whole code..in OP..That would let me to know the exact cause of your problem.
@DanielPatilea: In your original code label1 is no where appearing.. Can u explain a bit what you want to do when user put the number of players in JTextField and press OK ?
@DanielPatilea Ok..suppose I input 2 in JTextField and then press Ok..What those text labels should show as value?
|
1

The first issue I see is that you're trying to set the label text inside of the for loop where you should really be doing it outside:

for(int i = 0; i < toppings.length; i++){
    toppings[i] = textbox.getText();
}

label1.setText(toppings[0]);
// etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.