Hi all, I'm new to java programming but finding it rather fun and interesting. Right now I have

for(String name : chkNms) {

	    JCheckBox checkBox = new JCheckBox(name);
	    
	    checkBox.setMnemonic(KeyEvent.VK_C);
	    checkBox.setSelected(false);
	    
	   // checkBox.setActionCommand(name);
	    
	    add(checkBox);
	    
	    checkBox.addActionListener(this);
	}

to create all the check boxes I need, roughly 30 or so. The last line add's each of the check boxes to the listener method I've created. The question now is, how do I set the listener to do something based on whats checked?

What the check boxes are for is to function as a "on" or "off" switch of values to be searched for in a Excel document for data extraction. IE: there is a check box for date and job (titled properly) if both are checked on I want to pass/add the string values of "Date" and "Job" into an array. The array will then be used to check the top cell of each column to see if "Date" or "job" are present, if yes, extract that Column of data.

Thanks for you help and time.

Recommended Answers

All 28 Replies

In your listener, you can get a reference to the clicked object with e.getSource() , which you can then cast to JCheckBox . You can toggle your variable values based on JCheckBox.isSelected() .

Thank you Ezzaral, would you mind posting an example using Date and Job like I did earlier.

I already have code of my own to write here at work. Give it a go and if you have more questions post them here with your code.

One option would be to use a single listener for all of the check boxes to toggle values in a HashMap<String,Boolean> when they are checked/unchecked. You can then build your Excel filter criteria from the "true" values in that map.

class FilterCheckAction extends AbstractAction{
            public void actionPerformed(ActionEvent e) {
                filterMap.put(e.getActionCommand(), ((JCheckBox)e.getSource()).isSelected());
            }
        }

I already have a class that does

class ExpGui extends JFrame implements ActionListener

do I add

extends AbstractAction

to it and input the filterMap code to my listener or would it be best to create a new listener for the check boxes.

Also, with in said listener I assume I will need to create an array to hold the values provided by the filterMap, Or is filterMap the necessary array? Last question is how would I use or return the array for use?

Something I just thought about, while using the filterMap.put section of code, what happens when if the user changes their mind and unchecks something?

The state of the flags can be stored in a Map such as

Map<String, Boolean> filterMap = new HashMap<String, Boolean>();

Your listener just needs to set the value for that filter field option to true or false based on whether the box is checked

public void actionPerformed(ActionEvent e) {
        filterMap.put(e.getActionCommand(), ((JCheckBox)e.getSource()).isSelected());
    }

The method that actually builds the actual search string for Excel just needs to iterate the map and add the fields that are set to true. The ones that are false or not in the map at all don't matter.

Alternately, you could just add all of the JCheckBox components themselves to a List as you create them and iterate that list to build your filter string based on isSelected().

I like the sounds of that List idea.

in my creation string would it something like:

for(....){

List checkBox = new JCheckBox(name);
....
}

?

moving the

JCheckBox checkBox

; up to where I refrence the rest of the buttons and text field?

The way you create the boxes wouldn't change, you'd just need to create a list in your class to hold them

List<JCheckBox> checkList = new ArrayList<JCheckBox>();

and when you're adding them to the form (before/after, doesn't matter), add them to your list as well

checkList.add(checkBox);

Ok, need you to remember still new to this but I tried doing:

class BpsExportGUI extends JFrame implements ActionListener{
	JTextField fileIN; //Text Field Bull
	//JLabel fInHelp;//Labels time
	JFileChooser BpsFile = new JFileChooser(); 	//File Chooser
	JCheckBox Check;
	JButton expButton; 	//reference button object
	JButton opnButton;
	JButton reset;
	JButton all;
	
	//Panels
	
	List<JCheckBox> checkList = new ArrayList<JcheckBox>();
	
	JPanel inOut = new JPanel();
	JPanel ChckBx= new JPanel();
	
  BpsExportGUI(String title, String[] chkNms){ // Constructor 
	//Name Window  
	super(title);
	//construct TextField	//Set what to do
	fileIN = new JTextField(15);
	fileIN.addActionListener(this);
	fileIN.setEditable(false);
	//Label constructor
//	fInHelp =  new JLabel("OPen- Choose File to export");
	
	// construct all JButton & Actions
	expButton = new JButton("Export");
	expButton.setActionCommand("export");
	opnButton = new JButton("Open");
	opnButton.setActionCommand("Open");
	reset = new JButton("Reset");
	reset.setActionCommand("reset");
	all = new JButton("Check All");
	all.setActionCommand("all");
	
	// set the layout manager
	setLayout( new FlowLayout()); 
	inOut.add(fileIN);
	inOut.add(opnButton);
	inOut.add(expButton);
	ChckBx.setLayout(new GridLayout());
//	ChckBx.add(Check);
	
//	ChckBx.setLayout(new GridLayout());
//	ChckBx.add(Check);
	
/**
* Order for adding in the parts of the GUI will matter
**/
	//add Label to text field
	//add(fInHelp);
	//Add Text Field
	add(fileIN);
	//add buttons and check boxes
	add(opnButton);
	add(expButton);
	
	
	add(all);
	//CheckBox Creator
	for(String name : chkNms) {
		
		
		Check = new JCheckBox(name);
	    
		Check.setMnemonic(KeyEvent.VK_C);
		Check.setSelected(false);
	    	    
	   // checkBox.setActionCommand(name);
		Check.setActionCommand(name);
	    
	    
		add(Check);
	    checkList.add(Check);
	    
	    Check.addActionListener(this);
	}

	add(reset);


	//register listener to buttons
	expButton.addActionListener(this);
	opnButton.addActionListener(this);
	//Set what happens on hitting x(close) button- top right
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }

But eclipse is saying there is an error in the List<JCheckBox> ..... section, it cant not be resolved to a type.

Are you using Java 1.5 or later? Did you add List and ArrayList to your imports?

I'm using what ever the lastest version is from Sun, I downloaded it just last week. its like 7 or something. and I use list and array list else where to read a file, but that is essential CnP from a tutorial just to get it to work.

Post the exact error message.

Edit: Nevermind. Check your spelling of JCheckBox.

Haha, thats a derp moment right there

Ok, so now that that is done, lets get back to the listener.

what I need to do is something like:

for(int x=0; x< size(checkList); x++){
 if(Check.isSelected(true){
   filterArray.add(check);
 }
}

right?

Basically, yes, with some syntax correction. Is your search filter an array or a string that you pass to HSSF?

The way I figured to make the filter is to use a String array. That way, if its null, all values are taken, or it can have as many values as necessary depending upon the user. Right now I have a print to console method that takes List cellDataList; that has the info gained from the reader, and steps through it using to for statements, and just before printing the info out, i pass it into a double array called listCollecter by using the .toString(); command.

Ok so I i tried doing this:

f(evt.getActionCommand().equals("export")){
			 String file2Read;
			 for(int x=0; x< checkList.size();x++){
				 if(Check.isSelected()){
					 filter[x] = Check.getName();
					 System.out.print(filter[x]);
				 }
			 }				 
			file2Read = fileIN.getText();
			//file2Read = "NotConverted2.xls";	 
		//  	new BPSepcExporter().BPSReader(file2Read,filter);
	  }

I commented out the new bpsepcexpo...... section because I didn't want the export button to actually run any thing. Now I think I know where I messed up. What I should do is create a event item listener or create a new eventItem listner method for just the check boxes, that will add their name; which should be a string right?, to an array and then when the button is pressed it will pass that array on, with out actually modifying.

The problem I'm having with that right now, is understanding what happens if a user checks a item and decides they don't want that item any more and unchecks it.. how would I remove what that checkbox added from the array.

Just tried doing:

public void actionPerformed( ActionEvent evt)
  {
	  String[] filter = null;
	  
	  for(int x=0; x< checkList.size();x++){
		  if(evt.getActionCommand().equals(checkList)){
			 if(Check.isSelected()){
				 filter[x] = Check.getName();
			 }
		  }
	  }

and throwing a print statement in the export button's listener, got run time errors. Also nothing got printed even though I did check some checkboxes.

Several things here:

String[] filter = null;

You have to actually initialize the array before you can use it,

String[] filter = new String[size]; // proabably same size as number of checkboxes?

Not sure what you are trying to do with this

evt.getActionCommand().equals(checkList)

Comparing a string to an ArrayList?

Also can't figure what Check is here

Check.isSelected()

but you need to get() each checkbox from the checkList in your loop.

ok made the change:

String[] filter = new String[checkList.size()];

To set filter to the same size as the checklist and checkboxes.


the evt.getAction was an attempt to use the same if() statement form my button listneres to try and listen to the check boxes.

I don't think I understand how I get()? each check box from in the loop. Or fully comprehend how the listener is going to work with out a direct reference like int he case of my buttons.

How I'm think what will happen is:

if(check.isSelected(true)){
filter = chkNms; 
}
// where check names is the array that holds the names of all the
//"Filter" options in the form of a String array.

Then the export button just passes on filter to be used to filtered data extraction. However, getting to this point is the issue.

for(String name : chkNms) {
		
		
		Check = new JCheckBox(name);
	    
		Check.setMnemonic(KeyEvent.VK_C);
		Check.setSelected(false);
	    Check.setActionCommand(name);
		add(Check);
	    checkList.add(Check);
	    
	    Check.addActionListener(this);
	}

is how I created the Check boxes, but setting a listener to add, or remove, name (which is just a string variable passed in from chKNms; which is defined in the main) to the filter array is where I'm having trouble understanding what to do because its not as strait forward as the buttons where.

Basically all you are needing to do is

for(int i=0; i<checkList.size(); i++)                {
    JCheckBox cb = checkList.get(i);
    // if cb.isSelected() add cb.getText() to some list or array
}

I don't think you need to do that in your listener unless you are updating the results immediately as the user checks the boxes. You said your were extracting data from Excel, so I assumed the user made their choices and then hit "Go" or whatever. You can produce the list when they hit "Go".

I would actually recommend adding the field names to another List or Set instead of a fixed size array that will contain some nulls.

if(evt.getActionCommand().equals("export")){
			 String file2Read;
			 file2Read = fileIN.getText();
			 for(int i = 0; i < checkList.size(); i++){
				 JCheckBox cb = checkList.get(i);
				 if(cb.isSelected()){
					 filter[i] = cb.getText();
					 System.out.print(filter[i]+"\t");
				 }
			 }
		  	new BPSepcExporter().BPSReader(file2Read,filter);
	  }

From what you said, this is what I came up with, the print statement is just to check that something is going into filter. I'm still not certain how it worked though.

an new temporary check box is created with:

JCheckBox cb = checkList.get(i);

then the if statement check to see if it was selected?
if true then the filter gets the text associated with what ever checkList sub I is?

Yes, you're just putting the text of the selected checkboxes into your array. With a fixed size array though, the filter array will contain nulls in the slots that correspond to the unselected fields.

So if only box "1" and "3" is selected your array will contain ["1",null,"3",null,null...]. That is why I mentioned that you may want to add the fields to another list instead, so you don't have the nulls to mess with.

I can't make more specific suggestions because I don't know how you are actually using that filter against the Excel files.

couldn't the Null's just be prevented from being added, by doing say"

for(int i = 0; i < checkList.size(); i++){
	JCheckBox cb = checkList.get(i);
        //if cb[I] == null; do nothing 
        elseif(cb.isSelected()){
	 filter[i] = cb.getText();
	}
			 }

You can't prevent the element from being empty. If you don't select all of the check boxes you are going to have blanks in the array. You could certainly pre-fill the array with empty strings so they weren't actually null, but why not just use an ArrayList or some other collection of variable size to hold just the fields that you want to extract?

Yeah, i'm going to have to change something up and use arraylist some how, as it stands I get a nullpointerexception at run time.

Made the change:

public void actionPerformed( ActionEvent evt)
  {
	  ArrayList filter = new ArrayList();
	  
	  for(int x=0; x< checkList.size();x++){
	  }
	  
	  if(evt.getActionCommand().equals("reset")){
	  }
	 // if(evt.getActionCommand().equals("all")){
	//	}
	  if(evt.getActionCommand().equals("export")){
			 String file2Read;
			 file2Read = fileIN.getText();
			 for(int i = 0; i < checkList.size(); i++){
				 JCheckBox cb = checkList.get(i);
				 if(cb.isSelected()){
					 filter.add(cb.getText());
					 System.out.print(filter);
					 System.out.println();
				 }
			 }
		  	//new BPSepcExporter().BPSReader(file2Read,filter);
	  }

the output is:

[COMMITMENTTYPE]
[COMMITMENTTYPE, PONUMBER]
[COMMITMENTTYPE, PONUMBER, REVISION]
[COMMITMENTTYPE, PONUMBER, REVISION, JOB]
[COMMITMENTTYPE, PONUMBER, REVISION, JOB, PODESCRIPTION]
[COMMITMENTTYPE, PONUMBER, REVISION, JOB, PODESCRIPTION, LINETYPE]

Going to move the print statesments and that should printout what I'm expecting.

well every thing works, going to make a new thread though... my comparision section of code is broken, and I still get nullpointerException on run time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.