Home > front end >  Issue with java checkboxes and functions
Issue with java checkboxes and functions

Time:12-01

I am trying to create a simple checklist program to learn more about checkboxes, my main goal is to check all the boxes, have the frame close, and display a message saying you're done. I tried to have it all nestled in a function for the last part, as the frame and checkboxes seem to work, but found I couldn't write to variables inside of that specific function. I am looking mainly for different options to research, or possibly what I'm missing with my current implementation

public static void simpleChecklist(){
        JFrame f= new JFrame("Simple Checklist"); 
        f.setLayout(null);  
        f.setVisible(true);
        f.setSize(400,400);   
        //JButton done = new JButton();
        //done.setBounds(150,300,50,50);
        //f.add(done);
    
        boolean projectWork = false;
        JCheckBox ProjectWork = new JCheckBox("Project Work", projectWork);  
        ProjectWork.setBounds(100,50, 200,50);  
        boolean math = false;
        JCheckBox Math = new JCheckBox("Math", math);  
        Math.setBounds(100,100, 100,50);  
        boolean science = false;
        JCheckBox Science = new JCheckBox("Science", science);
        Science.setBounds(100,150,100,50);
        boolean compSci = false;
        JCheckBox CompSci = new JCheckBox("Comp Sci", compSci);
        CompSci.setBounds(100,200,100,50);
        boolean english = false;
        JCheckBox English = new JCheckBox("English", english);
        English.setBounds(100,250,100,50);
        boolean gov = false;
        JCheckBox Gov = new JCheckBox("Government", gov);
        Gov.setBounds(100,300,100,50);
        f.add(Gov);
        f.add(English);
        f.add(CompSci);
        f.add(Science);
        f.add(ProjectWork);  
        f.add(Math); 
        /*{done.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               

            }
        });*/


       
         class ItemListen implements ItemListener {

            public void itemStateChanged(ItemEvent arg0) {
    
                Gov.addItemListener(new ItemListen());
                English.addItemListener(new ItemListen());
                CompSci.addItemListener(new ItemListen());
                Science.addItemListener(new ItemListen());
                ProjectWork.addItemListener(new ItemListen());
                Math.addItemListener(new ItemListen());
               // Different Get Methods from ActionEvent
               /* arg0.getItemSelectable()
                arg0.getStateChange()
                arg0.getItem()*/
               
    
            }
    
        }
        boolean govDone = false;
        boolean englishDone = false;
        boolean compSciDone = false;
        boolean scienceDone = false;
        boolean projectWorkDone = false;
        boolean mathDone = false;


        if(Math.isSelected()){
            mathDone = true;
            checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
            System.out.println("1");
        }
        if(ProjectWork.isSelected()){
            projectWorkDone = true;
            checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
        }
        if(Science.isSelected()){
            scienceDone = true;
            checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
        }
        if(English.isSelected()){
            englishDone = true;
            checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
        }
        if(Gov.isSelected()){
            govDone = true;
            checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
        }
        if(CompSci.isSelected()){
            compSciDone = true;
            checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
        }
        

    }
    private static void checkIfDone(boolean projectWorkDone, boolean mathDone, boolean scienceDone,JFrame f, boolean compSciDone, boolean englishDone, boolean govDone){

        if (projectWorkDone == true && mathDone == true && scienceDone == true && compSciDone == true && englishDone == true && govDone == true){
            closeWindow(f);
            
        }
    }
    private static void closeWindow(JFrame f){
        f.dispose();
        JOptionPane.showMessageDialog(null,"Congrats! You Finished Your Work!!!");
    }

CodePudding user response:

Start by having a look at...

  • Simple

    import java.awt.EventQueue;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.border.EmptyBorder;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            public TestPane() {
                setBorder(new EmptyBorder(16, 16, 16, 16));
                setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                gbc.anchor = GridBagConstraints.LINE_START;
    
                JCheckBox projectWork = new JCheckBox("Project Work", false);
                JCheckBox math = new JCheckBox("Math", false);
                JCheckBox science = new JCheckBox("Science", false);
                JCheckBox compSci = new JCheckBox("Comp Sci", false);
                JCheckBox english = new JCheckBox("English", false);
                JCheckBox gov = new JCheckBox("Government", false);
    
                add(projectWork, gbc);
                add(math, gbc);
                add(science, gbc);
                add(compSci, gbc);
                add(english, gbc);
                add(gov, gbc);
    
                JCheckBox checkBoxes[] = new JCheckBox[] {
                    projectWork, math, science, compSci, english, gov
                };
                ActionListener listener = new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        boolean completed = true;
                        for (JCheckBox cb : checkBoxes) {
                            if (!cb.isSelected()) {
                                completed = false;
                                break;
                            }
                        }
                        if (completed) {
                            JOptionPane.showMessageDialog(TestPane.this, "All your class belong to us");
                            SwingUtilities.windowForComponent(TestPane.this).dispose();
                        }
                    }
                };
                for (JCheckBox cb : checkBoxes) {
                    cb.addActionListener(listener);
                }
            }
    
        }
    
        public static void simpleChecklist() {
            JFrame f = new JFrame("Simple Checklist");
            f.setLayout(null);
            f.setVisible(true);
            f.setSize(400, 400);
            //JButton done = new JButton();
            //done.setBounds(150,300,50,50);
            //f.add(done);
    
            boolean projectWork = false;
            JCheckBox ProjectWork = new JCheckBox("Project Work", projectWork);
            ProjectWork.setBounds(100, 50, 200, 50);
            boolean math = false;
            JCheckBox Math = new JCheckBox("Math", math);
            Math.setBounds(100, 100, 100, 50);
            boolean science = false;
            JCheckBox Science = new JCheckBox("Science", science);
            Science.setBounds(100, 150, 100, 50);
            boolean compSci = false;
            JCheckBox CompSci = new JCheckBox("Comp Sci", compSci);
            CompSci.setBounds(100, 200, 100, 50);
            boolean english = false;
            JCheckBox English = new JCheckBox("English", english);
            English.setBounds(100, 250, 100, 50);
            boolean gov = false;
            JCheckBox Gov = new JCheckBox("Government", gov);
            Gov.setBounds(100, 300, 100, 50);
            f.add(Gov);
            f.add(English);
            f.add(CompSci);
            f.add(Science);
            f.add(ProjectWork);
            f.add(Math);
            /*{done.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
    
    
                }
            });*/
    
            class ItemListen implements ItemListener {
    
                public void itemStateChanged(ItemEvent arg0) {
    
                    Gov.addItemListener(new ItemListen());
                    English.addItemListener(new ItemListen());
                    CompSci.addItemListener(new ItemListen());
                    Science.addItemListener(new ItemListen());
                    ProjectWork.addItemListener(new ItemListen());
                    Math.addItemListener(new ItemListen());
                    // Different Get Methods from ActionEvent
                    /* arg0.getItemSelectable()
                    arg0.getStateChange()
                    arg0.getItem()*/
    
                }
    
            }
            boolean govDone = false;
            boolean englishDone = false;
            boolean compSciDone = false;
            boolean scienceDone = false;
            boolean projectWorkDone = false;
            boolean mathDone = false;
    
            if (Math.isSelected()) {
                mathDone = true;
                checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
                System.out.println("1");
            }
            if (ProjectWork.isSelected()) {
                projectWorkDone = true;
                checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
            }
            if (Science.isSelected()) {
                scienceDone = true;
                checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
            }
            if (English.isSelected()) {
                englishDone = true;
                checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
            }
            if (Gov.isSelected()) {
                govDone = true;
                checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
            }
            if (CompSci.isSelected()) {
                compSciDone = true;
                checkIfDone(projectWorkDone, mathDone, scienceDone, f, compSciDone, englishDone, govDone);
            }
    
        }
    
        private static void checkIfDone(boolean projectWorkDone, boolean mathDone, boolean scienceDone, JFrame f, boolean compSciDone, boolean englishDone, boolean govDone) {
    
            if (projectWorkDone == true && mathDone == true && scienceDone == true && compSciDone == true && englishDone == true && govDone == true) {
                closeWindow(f);
    
            }
        }
    
        private static void closeWindow(JFrame f) {
            f.dispose();
            JOptionPane.showMessageDialog(null, "Congrats! You Finished Your Work!!!");
        }
    }
    

    CodePudding user response:

    Here is version of what you wanted to do. It is simpler as it uses a layout manager to align the checkboxes. The threads complicate matters and aren't completely necessary as I will explain later.

    import java.awt.Dimension;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    
    import javax.swing.BoxLayout;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class ItemListenerDemo extends JPanel implements ItemListener {
        JFrame f = new JFrame("Listener Demo");
        String[] subjects = { "CompSci", "Math", "History", "Sociology",
                "Chemistry" };
        int checkCount = 0;
            
        public static void main(String[] args) {
            SwingUtilities
                    .invokeLater(() -> new ItemListenerDemo().start());
        }
        // basic boiler plate
        public void start() {
            // add the panel to the frame
            f.add(this); 
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           
            // resize and position the components
            f.pack();
    
            // BoxLayout will align them from top to bottom.
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    
            // install the checkboxes
            // add the subject, the listener, and add to the panel
            for (String subject : subjects) {
                JCheckBox b = new JCheckBox(subject);
                b.addItemListener(this);
                add(b); // add to panel
            }
            // center on screen
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            
            // wait for a signal to check and see if all boxes are checked
            new Thread(() -> {
                synchronized (this) {
                    while (true) {
                        try {
                            wait();
                        } catch (InterruptedException ie) {
                        }
                        if (checkCount == subjects.length) {
                            int action = JOptionPane.showConfirmDialog(null,
                                    "Congrats! You Finished Your Work!!!\n Do you want to quit?");
                            if (action == JOptionPane.YES_OPTION) {
                                System.exit(0);
                            }
                        }
                    }
                }
            }).start();
        }
        
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
        
        public void itemStateChanged(ItemEvent e) {
            Object source = e.getSource();
            if (source instanceof JCheckBox) {
                JCheckBox b = (JCheckBox) source;
                // adjust the checkCount based on this checkboxes status.
                checkCount  = b.isSelected() ? 1 : -1;
                // signal those threads waiting.
                synchronized (this) {
                    notify();
                }
            }
        }
    }
    

    The purpose of the thread two fold.

    Notice my SwingUtilities statement. That starts the whole process int the EDT which included the while(true) loop. So the EDT would never exit since the loop would never end. The loop waits for the Event Dispatch Thread (EDT) to finish it's business and then have the other thread check the status of the checkCount. If I had done this check in the itemStateChanged method, the last checkbox would not have visibly appeared to be checked since I was still in the EDT and the painting could not finish.

  • Related