Search code examples
javajbuttonactionlistenertextfieldjcheckbox

How to connect the JCheckBox and JButton to show the number JAVA


private JTextField textFieldSum = new JTextField(1);

public Count() {
    super("Project 2");
    super.setBounds(150, 150, 500, 500);
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    gridBagLayout.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
    super.getContentPane().setLayout(gridBagLayout);
    JCheckBox chckbxNewCheckBox1 = new JCheckBox("A");
    add(chckbxNewCheckBox1);
    textFieldSum.setEditable(false);
    add(textFieldSum);
    JButton btnYes = new JButton("YES");
    add(btnYes);
    BufferedReader reader;
    int counterA = 0;
    try {
        reader = new BufferedReader(new FileReader("in.txt"));
        int data;
        while ((data = reader.read()) != -1) {
            char charA = 'A';
            if (charA == (char) data) {
                counterA++;
            }  
        }
        textFieldSum.setText(String.valueOf(counterA));
        reader.close();
    } catch (IOException ioException) {
        System.err.println("Error Opening File: Terminating");
        System.exit(1);
    }   
}

Im sorry yall, but I have no idea how to use the actionListener in this case. I write a method to count a letter A in a file called in.txt and I created checkbox and a button. I want to connect the checkbox and button together. If I click the checkbox first and click button yes second, it will show me the how many letters in that file in the textfield. But I try so hard but I cant connect them lol.


Solution

  • At first define a variable in your class

    int static checkboxcheck = 0;
    

    then implement onClickListener for your componenets after their declaration for your checkbox as below :

    chckbxNewCheckBox1.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(schckbxNewCheckBox1.isChecked()){
                    checkboxcheck = 1;
                }else{
                    checkboxcheck = 0;
                }
            }
        });
    

    and your button like this :

     btnYes.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(checkboxcheck == 1)
                {
                 // do what ever you want here
                }
                 else
                 {
                  checkboxcheck = 0;
                 }
            }
        });