Is it possible to extract Strings out of ListSelectionEvents in java swing?

127 Views Asked by At

I am using JList of Strings in java swing. I want to have a ListSelectionListener which returns the String of the Listentry, that was selected by the user. But I can't reach the String itself. The only thing that I could find

private void registerListeners()
{
    gui.getListMeasurements().addListSelectionListener(new ListSelectionListener()
    {

        @Override
        public void valueChanged(ListSelectionEvent event)
        {
            System.out.println(event.getSource());

        }
    });
}

Outputs the following 4 times: javax.swing.JList[,0,0,240x340,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]

Nothing in this output refers to the String selected in the list. Neither can I find any useful method for the event. Is it possible to extract Strings the way I described?

1

There are 1 best solutions below

1
MadProgrammer On BEST ANSWER
gui.getListMeasurements().addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
            return;
        }
        if (e.getSource() instanceof JList) {
            JList list = (JList) e.getSource();
            int index = list.getSelectedIndex();
            Object element = list.getModel().getElementAt(index);
            if (element instanceof String) {
                System.out.println("Selected value at " + index + " = " + element);
            }
        }
    }
});

Helpful links: