1

我怎样才能得到一个选定的项目?

我的代码中有一个简单的要求:我需要获得一个选定的项目来实现ActionListener启用 a 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"),但我现在不知道要这样做。

4

2 回答 2

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
            }
        });  
于 2013-10-15T21:22:05.100 回答
1

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

查看如何使用按钮如何编写动作侦听器以了解有关将动作侦听器注册到按钮的更多详细信息,以及如何使用列表了解有关使用JLists的详细信息

于 2013-10-15T21:22:31.193 回答