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

时间:2015-11-19 05:18:09

标签: java jbutton actionlistener textfield jcheckbox

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,我创建了复选框和一个按钮。我想将复选框和按钮连接在一起。如果我先单击复选框并单击按钮yes,它将显示文本字段中该文件中的字母数。但是我努力尝试但是我无法将它们联系起来哈哈。

1 个答案:

答案 0 :(得分:0)

首先在班级中定义一个变量

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