是否可以在java swing中从ListSelectionEvents中提取字符串?

时间:2018-03-01 01:15:58

标签: java swing listselectionlistener

我在java swing中使用字符串的JList。我想要一个ListSelectionListener,它返回用户选择的Listentry的String。但我无法达到字符串本身。我唯一能找到的东西

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

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

        }
    });
}

输出以下4次:javax.swing.JList [,0,0,240x340,alignmentX = 0.0,alignmentY = 0.0,border =,flags = 50331944,maximumSize =,minimumSize =,preferredSize =,fixedCellHeight = -1, fixedCellWidth = -1,horizo​​ntalScrollIncrement = -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]

此输出中没有任何内容引用列表中选定的字符串。我也找不到任何有用的方法。 是否有可能按照我描述的方式提取字符串?

1 个答案:

答案 0 :(得分:1)

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);
            }
        }
    }
});

有用的链接: