从Java中的JList获取选定的值 [英] Get the selected values from JList in Java

查看:98
本文介绍了从Java中的JList获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

推荐答案

最初在JList中未选择任何元素,因此,如果不从列表中选择元素,则返回的索引将为-1,返回值将为空值. 尝试以下代码,然后从列表中选择和元素,然后测试其是否有效:

Initially no element is selected in JList so 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:

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

这篇关于从Java中的JList获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆