从 Java 中的 JList 获取选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28852864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:17:00  来源:igfitidea点击:

Get the selected values from JList in Java

javaswingactionlistenerjlist

提问by Adrian Trifan

How can i get the selected value from Jlist? I tried the following code, but all variables are displayed null. Why index variable is null?

如何从 Jlist 中获取选定的值?我尝试了以下代码,但所有变量都显示为空。为什么索引变量为空?

 public class GetSelectedValueFromJList extends JFrame implements ActionListener {
    private JList list;
    private JButton checkButton;

    public GetSelectedValueFromJList() {



        String[] nameList = { "Value 1", "Value 2", "Value 3", "Value 4", "Value 5"};
        list = new JList(data);
        checkButton = new Button("Check");
        button.addActionListener(this);

        //add list to frame
        add(list);
        add(checkButton);

    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getCommand().equals("Check"))
        {
            int index = list.getSelectedIndex();
            System.out.println("Index Selected: " + index);
            String s = (String) list.getSelectedValue();
            System.out.println("Value Selected: " + s);
        }
    }

回答by Naruto Biju Mode

Initially no element is selected in JListso if you don't select an element from the list the returned index will be -1 and returned value will be null. try this code and select and element from the list then test if it works:

最初没有选择任何元素,JList因此如果您不从列表中选择元素,则返回的索引将为 -1,返回值将为空。试试这个代码并从列表中选择和元素然后测试它是否有效:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;

public class Frame extends JFrame implements ActionListener
{
    private JList list;
    private JButton checkButton;

    public Frame()
    {
        setBounds(100,100,300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String[] nameList = { "Value 1", "Value 2", "Value 3", "Value 4", "Value 5" };
        list = new JList(nameList);
        checkButton = new JButton("Check");
        checkButton.addActionListener(this);

        // add list to frame
        JPanel panel = new JPanel();
        panel.add(list);
        panel.add(checkButton);
        add(panel);
        setVisible(true);
    }

    public static void main(String[] args)
    {
        new Frame();
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("Check"))
        {
            int index = list.getSelectedIndex();
            System.out.println("Index Selected: " + index);
            String s = (String) list.getSelectedValue();
            System.out.println("Value Selected: " + s);
        }
    }
}

回答by Andrew Thompson

This is not an answer, since it does not really address the stated problem. As such I'll have to delete it soon. I am posting it to show a slight variant of that code (as an MCVE) to demonstrate that there is no nullseen in the output if an item in the list is selected. Well, that and to encourage you to post an MCVEof code that actually shows the stated problem.

这不是答案,因为它并没有真正解决所述问题。因此,我必须尽快将其删除。我张贴它是为了显示该代码的一个轻微变体(作为MCVE),以证明如果选择了列表中的一个项目,则null输出中没有看到。好吧,那并鼓励您发布实际显示所述问题的代码的MCVE

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

public class GetSelectedValueFromJList
        extends JFrame implements ActionListener {

    private JList list;
    private JButton button;

    public GetSelectedValueFromJList() {
        String[] nameList = {
            "Value 1", "Value 2", "Value 3", "Value 4", "Value 5"
        };
        list = new JList(nameList);
        list.setSelectedIndex(2);

        button = new JButton("Check");
        button.addActionListener(this);

        add(list);
        add(button, BorderLayout.PAGE_END);

        pack();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Check")) {
            int index = list.getSelectedIndex();
            System.out.println("Index Selected: " + index);
            String s = (String) list.getSelectedValue();
            System.out.println("Value Selected: " + s);
        }
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new GetSelectedValueFromJList().setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

回答by chitharth

This code will get more than one selected values...

此代码将获得多个选定值...

 int[] selectedIndices = jList1.getSelectedIndices();
String[] myArray = new String[50];
for (int i = 0; i < selectedIndices.length; i++) {
               myArray[i] =  String.valueOf(jList1.getModel().getElementAt(selectedIndices[i]));
        }

this code will get one value...

此代码将获得一个值...

String myString = String.valueOf(jList1.getModel().getElementAt(jList1.getSelectedIndex());

or

或者

 String myString = String.valueOf(jList1.getSelectedValue());