如何连接 JCheckBox 和 JButton 以显示数字 JAVA

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);
    }   
}

对不起大家,但我不知道在这种情况下如何使用 actionListener。我编写了一个方法来计算一个名为 in.txt 的文件中的字母 A,并创建了复选框和按钮。我想将复选框和按钮连接在一起。如果我先单击复选框,然后单击按钮是,它会在文本字段中显示该文件中的字母数。但是我很努力,但我无法连接它们哈哈。

首先在你的class

中定义一个变量
int static checkboxcheck = 0;

然后在声明后为您的组件实现 onClickListener 对于您的复选框如下:

chckbxNewCheckBox1.setOnClickListener(new OnClickListener() {

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

你的按钮是这样的:

 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;
             }
        }
    });