How to use the selection of JCheckBoxes to use?

I have a checkbox in a JFrame. When I check it, I want to display in the command window that it was selected. Below is the code I'm working with. It compiles and runs without errors, but I don’t get the “one that was selected” in the window when I check the box.

 public Checklist() {

    ...

    JCheckBox one = new JCheckBox("CT scan performed");
    one.addItemListener(new CheckBoxListener());

    }
        private class CheckBoxListener implements ItemListener{
        public void itemStateChanged(ItemEvent e)
        {
        if(e.getSource()==one){ if(one.isSelected()){
        System.out.println("one has been selected");
            }
            else{System.out.println("nothing");}
            }
     }}
+3
source share
5 answers

I checked this simple example and it works fine (it writes "one has been selected"when the checkbox is selected and "nothing"when you cancel it):

import javax.swing.*;
import java.awt.event.*;

public class Example extends JFrame{
    public JCheckBox one;

    public Example() {
        one = new JCheckBox("CT scan performed");
        one.addItemListener(new CheckBoxListener());
        setSize(300,300);
        getContentPane().add(one);
        setVisible(true);
    }

    private class CheckBoxListener implements ItemListener{
        public void itemStateChanged(ItemEvent e) {
            if(e.getSource()==one){
                if(one.isSelected()) {
                    System.out.println("one has been selected");
                } else {System.out.println("nothing");}
            }
        }
    }

    public static void main(String[] args) {
        new Example();
    }
}

In your example, it seems to be onedeclared in the constructor CheckList(). Are you sure you can access it in the inner class CheckBoxListener?

+5
source

, , !

, :

public class Checklist extends JFrame {
    private JCheckBox one;

    public Checklist() {
        JCheckBox one = new JCheckBox("CT scan performed");
        one.addItemListener(new CheckBoxListener());
        this.add(one);
    }
}

"", " JCheckBox ", , "JCheckBox one =..." . ,

one.addItemListener(new CheckBoxListener());
this.add(one);

"" , "" !

,

if(e.getSource() == one)

"" , , !

"JCheckBox" - "" "" .

, - , :

public class Checklist extends JFrame {
    private JCheckBox one;

    public Checklist() {
        JCheckBox anotherOne = new JCheckBox("CT scan performed");
        anotherOne.addItemListener(new CheckBoxListener());
        this.add(anotherOne);
    }
}

...

if(e.getSource() == one)  //not equal to anotherOne!
+4

, , ), , . . addActionListener.

0

, , , , , . ActionListener , .

0

,

if(e.getSource()==one){

? , . .

0

Source: https://habr.com/ru/post/1793108/


All Articles