-2

I have a problem with ItemListeners. Basially, I want to query the database to get some data and put them into Objects following the DAO Pattern. The thing is, when I put an ArrayList of CheakBoxes, I can't figure out how to add Listeners to them.

I have tried to add ItemListener before putting them in their container through loop. I have also tried to add ItemListeners after adding them to the container but also with no avail.

I have tested my script for 1 chekBox only, it works. When it comes to the ArrayList, i have this error Message: Cannot refer to the non-final local variable jCheckBox defined in an enclosing scope

The following code is another test, just to see if something was incorrect on my program, but it seems to give me same Issue when adding the listener to the ArrayList objects

package test;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {
private static ArrayList<JCheckBox> jCheckBoxs;
private static JFrame jFrame=new JFrame();

public static void main(String[] args) {
    init();
}
private static void init() {

    jFrame.setSize(new Dimension(400,400));
    jFrame.setTitle("test");

    JPanel jp=new JPanel();
    jCheckBoxs=new ArrayList<JCheckBox>();
    addArray("A");
    addArray("B");
    addArray("C");
    jp.add(jCheckBoxs.get(0));

    jp.add(jCheckBoxs.get(1));

    jp.add(jCheckBoxs.get(2));

    jFrame.getContentPane().add(jp);
    jFrame.setVisible(true);
}
private static void addArray(String msg) {
    JCheckBox jCheckBox=new JCheckBox();
    jCheckBox.setText(msg);
    jCheckBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            System.out.println(jCheckBox.getName());
        }
    });
}
}
  • Even if you fixed your addArray method, by making the jCheckBox local variable `final`, the method makes no sense since you're adding no JCheckBoxes to the ArrayList. – Hovercraft Full Of Eels Jul 27 '18 at 14:32
  • forgot to add the object to the arraylist ... as i said its not my original program its just a test but my problem is the listeners not the behaviour i want from the arraylist –  Jul 27 '18 at 14:35
  • 1
    You should show reasonable code in your post, code that runs and makes logical sense. As for you error message, again, make the local variable `final`. – Hovercraft Full Of Eels Jul 27 '18 at 14:41
  • [When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. Click this comment to find out how to provide what we need to help you.](https://stackoverflow.com/help/mcve) –  Jul 27 '18 at 15:37

1 Answers1

0
  • If you're going to refer to a local variable within an anonymous inner class, as you're doing, you need to make the local variable final, as has been discussed in many similar questions
  • You're not adding the JCheckBoxes to the ArrayList or the GUI, so your code is meaningless
  • Don't use absolute ArrayList indices, since you're asking for exceptions. In your code above the ArrayList size is 0, so this code will result in an index out of bounds exception
  • Most all of that code should not be static. Use instance fields and instance methods. Only the main method should be static.

For example:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

@SuppressWarnings("serial")
public class MultCheckBoxes extends JPanel {
    private List<JCheckBox> checkBoxes = new ArrayList<>();
    private JTextArea showSelectionTArea = new JTextArea(25, 50);
    private JPanel checkBoxPanel = new JPanel(new GridLayout(0, 1));
    private ItemListener myItemListener = new MyItemListener();

    public MultCheckBoxes() {
        showSelectionTArea.setFocusable(false); // so user can't enter text

        JPanel wrapperPanel = new JPanel(new BorderLayout());
        wrapperPanel.add(checkBoxPanel, BorderLayout.PAGE_START);

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(new JButton(new GetAllStatesAction()));

        setLayout(new BorderLayout());
        add(new JScrollPane(showSelectionTArea));
        add(wrapperPanel, BorderLayout.LINE_END);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    public void addCheckBox(String name) {
        JCheckBox checkBox = new JCheckBox(name);
        checkBox.addItemListener(myItemListener);
        checkBoxes.add(checkBox);
        checkBoxPanel.add(checkBox);
        revalidate();
        repaint();
    }

    private class MyItemListener implements ItemListener {

        @Override
        public void itemStateChanged(ItemEvent itemEvt) {
            // The ItemEvent object will give us the JCheckBox that was changed
            JCheckBox checkBox = (JCheckBox) itemEvt.getSource();

            // get its text and its state
            String text = checkBox.getText();
            String select = itemEvt.getStateChange() == ItemEvent.SELECTED ? "selected" : "unselected";

            // display this in the JTextArea
            showSelectionTArea.append(text + ": " + select + "\n");
        }        
    }

    private class GetAllStatesAction extends AbstractAction {
        public GetAllStatesAction() {
            super("Get All CheckBox States"); // button's text
            putValue(MNEMONIC_KEY, KeyEvent.VK_A); // mnemonic key
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            showSelectionTArea.append("\n");
            showSelectionTArea.append("All CheckBox States: \n");
            for (JCheckBox jCheckBox : checkBoxes) {
                String text = jCheckBox.getText();
                String select = jCheckBox.isSelected() ? "selected" : "unselected";

                showSelectionTArea.append(text + ": " + select + "\n");
            }
            showSelectionTArea.append("\n");
        }
    }

    private static void createAndShowGui() {
        MultCheckBoxes mainPanel = new MultCheckBoxes();
        mainPanel.addCheckBox("Box A");
        mainPanel.addCheckBox("Box B");
        mainPanel.addCheckBox("Box C");
        mainPanel.addCheckBox("Box D");
        mainPanel.addCheckBox("Box E");

        JFrame frame = new JFrame("MultCheckBoxes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373