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