Java- how do I increment a variable whenever a file selected in JList?

Go To StackoverFlow.com

1

What I'm having problems with is that I have a list of 10 files in a JList. On a JButton, I have "attached file(s) 0." What I'm trying to achieve is when a user clicks on a file in the JList, the variable fileCount (represents the '0') will increment. Here is the code:

@Override
public void mouseClicked(MouseEvent arg0) {
        int idx = list_fileListing.getSelectedIndex();
        String eFiles[] = ig.getListOfFiles();

       if(idx == list_fileListing.getSelectedIndex()){
    fileCount++;
    }
}

Basically, if a file is selected, increment fileCount. Any suggestions as to how to accomplish this?

2012-04-03 23:34
by SpicyWeenie


3

The JButton class has a setText() method like many of the other Swing component classes. You can use this method to overwrite the text that is currently on the JButton.

ex:

if(idx == list_fileListing.getSelectedIndex())
{
    fileCount++;
    yourButtonName.setText("attached file(s) " + fileCount);
}

hope this helps.

2012-04-03 23:40
by Hunter McMillen
That worked, but now the new problem is only registering 1 file if you decide to click on a different file in the list. Currently from your answer, every time a file is clicked, the fileCount will increment regardless of how many files I click on. What I need is every time the selection change, the fileCount resets to 0, then recounts selected files - SpicyWeenie 2012-04-04 01:20
Ok, well what event fires when you select more than one file? Once you figure what event is firing, you can check to see how many items were selected and increment by that amount - Hunter McMillen 2012-04-04 01:25
There is no even firing that I know of. After creating my list and testing it, I could already select multiple files in my list using Shift/Ctrl + click. Still trying to search if there is something that can check if the selection changed, but no luck so far.. - SpicyWeenie 2012-04-04 01:31
Try using the getSelectedIndices() method from the JList class, it should return an array of all the selected indexes. http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getSelectedIndices( - Hunter McMillen 2012-04-04 01:36
Found the solution. ListSeletionListener. Then used getSelectedValueList and put it into a List, then got the size of it and put it into fileCount. Now it automatically updates the count according to whats selected. Thanks for the help : - SpicyWeenie 2012-04-04 02:36
Ads