Search code examples
javaswingactionlistenerjcheckbox

JCheckBox issue in Java?


This is my code here in this i want to get output as following but some error is there

---Outputs----

Name Arun.Gender Male. He likes nothing.

Name Arun.Gender Male. He likes Cricket only

Name Arun.Gender Male. He likes Cricket and Tennis.

Name Arun.Gender Male. He likes Cricket ,Football and Tennis

/*
 * Register.java
 *
 * Created on 8 October, 2014, 9:27 AM
 */

package Register;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author  DELL
 */
public class Register extends javax.swing.JFrame {

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

    /** 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() {

    bg = new javax.swing.ButtonGroup();
    buttonGroup2 = new javax.swing.ButtonGroup();
    jPanel1 = new javax.swing.JPanel();
    rb_female = new javax.swing.JRadioButton();
    cb_cricket = new javax.swing.JCheckBox();
    txt_name = new javax.swing.JTextField();
    lbl_name = new javax.swing.JLabel();
    cb_tennis = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    ta_show = new javax.swing.JTextArea();
    rb_male = new javax.swing.JRadioButton();
    cb_football = new javax.swing.JCheckBox();
    btn_show = new javax.swing.JButton();
    lbl_hobbies = new javax.swing.JLabel();
    lbl_gender = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Register", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 14))); // NOI18N

    bg.add(rb_female);
    rb_female.setFont(new java.awt.Font("Times New Roman", 1, 14));
    rb_female.setText("Female");

    cb_cricket.setFont(new java.awt.Font("Times New Roman", 1, 14));
    cb_cricket.setText("Cricket");

    lbl_name.setFont(new java.awt.Font("Times New Roman", 1, 14));
    lbl_name.setText("Name");

    cb_tennis.setFont(new java.awt.Font("Times New Roman", 1, 14));
    cb_tennis.setText("Tennis");

    ta_show.setColumns(20);
    ta_show.setRows(5);
    jScrollPane1.setViewportView(ta_show);

    bg.add(rb_male);
    rb_male.setFont(new java.awt.Font("Times New Roman", 1, 14));
    rb_male.setText("Male");

    cb_football.setFont(new java.awt.Font("Times New Roman", 1, 14));
    cb_football.setText("Football");

    btn_show.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
    btn_show.setText("Show");

    lbl_hobbies.setFont(new java.awt.Font("Times New Roman", 1, 14));
    lbl_hobbies.setText("Hobbies");

    lbl_gender.setFont(new java.awt.Font("Times New Roman", 1, 14));
    lbl_gender.setText("Gender");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbl_gender)
            .addComponent(lbl_name)
            .addComponent(lbl_hobbies)
            .addComponent(btn_show))
        .addGap(30, 30, 30)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(cb_cricket)
                .addComponent(cb_football)
                .addComponent(cb_tennis))
            .addGap(103, 103, 103))
            .addGroup(jPanel1Layout.createSequentialGroup()
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(rb_male)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(rb_female))
            .addComponent(txt_name, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(lbl_name)
            .addComponent(txt_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(32, 32, 32)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(lbl_gender)
            .addComponent(rb_female)
            .addComponent(rb_male))
        .addGap(35, 35, 35)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(lbl_hobbies)
            .addComponent(cb_cricket))
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cb_football)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cb_tennis)
            .addGap(18, 18, 18)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(105, 105, 105)
            .addComponent(btn_show)))
        .addContainerGap())
    );

    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(38, 38, 38)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGap(57, 57, 57))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
        .addGap(19, 19, 19)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGap(23, 23, 23))
    );

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

    public void initListener() 
    {
    ActionListener al=new ActionListener() 
    {

        String name;
        String gender;  
        String hobbies[] = new String[10];            


        String data1;
        String data2;
        String data3;
        int i=-1;
        String show;


        public void actionPerformed(ActionEvent e) 
        {
        name = txt_name.getText();

        data1="Name is "+name+". ";

        //*************************************

        if (rb_male.isSelected()) 
        {
            gender = "Male";

        } 
        else if (rb_female.isSelected()) 
        {
            gender = "Female";
        }


        data2="Gender  "+gender+". ";


         if(gender.equals("Male"))
        {
            data3="He likes ";
        }
        else 
        {
            data3="She likes ";
        }




        //*************************************

        String b = "";

        if (cb_cricket.isSelected()) 
        {
            hobbies[i++] = "Cricket";

        }
        if (cb_football.isSelected()) 
        {
            hobbies[i++] = "Football";

        }
        if (cb_tennis.isSelected()) 
        {
            hobbies[i++] = "Tennis";

        }
        System.out.println("iSelected= " + i);

        if (i == -1) 
        {
            b = " nothing";
        } 
        else 
        {
            for (int j = 0; j < i; j++) 
            {

            if (i > 0) 
            {
                if (j < i - 2) 
                {
                b = b + hobbies[j] + ", ";
                } 
                else if (j == i - 2) 
                {
                b = b + hobbies[j] + " and ";
                } 
                else 
                {
                b = b + hobbies[j] + ".";
                }
            } 
            else if (i == 0) 
            {

                b = b + hobbies[j] + " only";

            }
            }
        }
        show=data1+data2+data3+b;
        ta_show.setText(show);


        //************************************* 







        //*************************************
          // ta_show.setText(data1+data2+b);
        }



    };
    btn_show.addActionListener(al);
    }



    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
        new Register().setVisible(true);
        }
    });
    }

    // Variables declaration - do not modify
    private javax.swing.ButtonGroup bg;
    private javax.swing.JButton btn_show;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JCheckBox cb_cricket;
    private javax.swing.JCheckBox cb_football;
    private javax.swing.JCheckBox cb_tennis;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbl_gender;
    private javax.swing.JLabel lbl_hobbies;
    private javax.swing.JLabel lbl_name;
    private javax.swing.JRadioButton rb_female;
    private javax.swing.JRadioButton rb_male;
    private javax.swing.JTextArea ta_show;
    private javax.swing.JTextField txt_name;
    // End of variables declaration

}

the mistake part of this code is

        String b = "";

        if (cb_cricket.isSelected()) 
        {
            hobbies[i++] = "Cricket";

        }
        if (cb_football.isSelected()) 
        {
            hobbies[i++] = "Football";

        }
        if (cb_tennis.isSelected()) 
        {
            hobbies[i++] = "Tennis";

        }
        System.out.println("iSelected= " + i);

        if (i == -1) 
        {
            b = " nothing";
        } 
        else 
        {
            for (int j = 0; j < i; j++) 
            {

            if (i > 0) 
            {
                if (j < i - 2) 
                {
                b = b + hobbies[j] + ", ";
                } 
                else if (j == i - 2) 
                {
                b = b + hobbies[j] + " and ";
                } 
                else 
                {
                b = b + hobbies[j] + ".";
                }
            } 
            else if (i == 0) 
            {

                b = b + hobbies[j] + " only";

            }
            }
        }
        show=data1+data2+data3+b;
        ta_show.setText(show);

Solution

  • There are multiple problems there.

    Firstly one of the genders should be pre-selected. You get an NullPointerException if none is.

    And for the ArrayIndexOutOfBoundsException I propose using a list:

    LinkedList<String> hobbies = new LinkedList<String>(); 
    
    //...
    
     hobbies.clear();
    
        if (cb_cricket.isSelected()) 
        {
            hobbies.add("Cricket");
    
        }
        if (cb_football.isSelected()) 
        {
            hobbies.add("Football");
    
        }
        if (cb_tennis.isSelected()) 
        {
            hobbies.add("Tennis");
    
        }
    
        if (hobbies.size() == 0) 
        {
            b = " nothing";
        } 
        else 
        {
            for (int j = 0; j < hobbies.size(); j++) 
            {
                if( j > 0)
                {
                    if(j == hobbies.size()-1)
                    {
                        b += " and ";
                    }
                    else
                    {
                        b += ", ";
                    }
                }
    
                b+= hobbies.get(j);
            } 
    
            if (hobbies.size() == 1) 
            {
    
                b += " only";
    
            }
    
            b += ".";
    
        }
    

    Using a LinkedList you get a better scaleable result.

    Bonus Points for replacing b with a StringBuilder.