如何查看JList中的用户选择了什么?

时间:2014-04-08 00:26:32

标签: java swing jbutton jlist

最近,我一直在研究Java Jukebox程序。到目前为止,在该节目中,用户从JList中选择一首歌曲,然后点击播放" Play" JButton的。我需要做的是让程序找出从列表中选择的选项,然后启动相应的构造函数。有关如何做到这一点的任何建议吗?

-John

3 个答案:

答案 0 :(得分:1)

查看JList getSelected种方法,特别是getSelectedValue()getSelectedValues()

答案 1 :(得分:1)

查看JList#getSelectedIndex和/或Jlist#getSelectedIndices,它会告诉您当前选择的内容。

请查看How to Use Lists了解详情

答案 2 :(得分:0)

以下是代码:

    package box.java.juke.airtime;

    import java.awt.BorderLayout;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.ListSelectionModel;

    public class JukeBox {
     public static final int WIDTH = 300;
     public static final int HEIGHT = 400;
     public static final String NAME = "Java JukeBox";

public static void main(String[] args) {
    JFrame j = new JFrame(NAME);
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    j.setSize(WIDTH, HEIGHT);
    j.setVisible(true);
    j.setLocationRelativeTo(null);

    String[] songs = { "Cipher", "Flight", "To the Stars",
            "Last Train to Paradise", "Surge" };
    @SuppressWarnings({ "unchecked", "rawtypes" })
    JList list = new JList(songs);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    j.add(list);
    System.out.println(list.getSelectedValue());
    JButton b = new JButton();
    b.setText("Play");
    j.getContentPane().add(BorderLayout.SOUTH, b);
    j.setResizable(false);
}

}