Swing JList和DefaultListModel。

时间:2013-10-15 21:19:31

标签: java swing jbutton actionlistener jlist

我如何获得所选项目?

我的代码中有一个简单的要求:我需要选择一个项目才能实现ActionListener启用JButton

    public class Tela extends JFrame{
    private static final long serialVersionUID = 1L;
    private DefaultListModel<String> model;
    private JList<String> list;

    public Tela(){
        setTitle("Maquina de Refrigerante");
         String labels[] = { "Coca-Cola", "Fanta Laranja", "Fanta-Uva", 
                 "Sprite"};

        //Cria os Paineis no Frame
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        JPanel leftPanel = new JPanel();
        JPanel rightPanel = new JPanel();
        JPanel downPanel = new JPanel();
        leftPanel.setLayout(new BorderLayout());

        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        list = new JList<String>(labels);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

        JScrollPane pane = new JScrollPane();
        pane.getViewport().add(list);  
        leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        leftPanel.add(pane);

        final JButton comprar = new JButton("Comprar");
        comprar.setEnabled(false);       
        rightPanel.add(comprar);
        rightPanel.add(Box.createRigidArea(new Dimension(0,4)));
        rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

        panel.add(leftPanel);
        panel.add(rightPanel);
        panel.add(downPanel);
        add(panel);

        setSize(450, 350);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        comprar.addActionListener(new Paga());
    }


}

我想实现一个ActionListener来获取所选项目,因此启用jbutton("Comprar"),但我现在还不知道这样做。

2 个答案:

答案 0 :(得分:1)

getSelectedIndex()getSelectedIndices()将提供所选项目的索引

除了 MadProgrammer 的回答之外,最好使用ListSelectionListener监听选择状态更改事件。 JList负责监听选择模型中的选择状态更改,并通知给定的侦听器每个更改。使用方法如下:

jList.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent evt) {
               selectedValues = jList1.getSelectedValuesList(); 
                        // it will return a list of values
                        //evt.getFirstIndex() - the index of last selected item
                       //evt.getLastIndex() - the index of current selected item
            }
        });  

答案 1 :(得分:1)

您可以使用JList#getSelectedValue返回当前选中的项目。

请查看How to use buttonsHow to write an Action Listener,了解有关向按钮注册操作侦听器的详细信息,以及How to use lists有关使用JList的详细信息