JList getSelectedValue()

时间:2015-03-15 11:40:47

标签: java swing jlist

enter image description here

你好。我已经在google上彻底搜索了如何在JList中获取selectedValue并使用该值来计算菜单的价格,如下图所示。但是,我无法找到实现按钮计算功能的方法。有关问题的描述,请参阅下图。

    import javax.swing.*;

import java.awt.Font;
import java.awt.event.*;

public class JResto extends JFrame implements ActionListener {
    private JTextField t1;
    private JButton b1;
    private JList list;
    private String[] values = {"Fried Rice (Rs 150)", "Fried Noodle (Rs 125)", "Chop Soy (Rs 75)", "Wang Tang (Rs 35)"};

    public JResto(){
    super("Sumen Restaurant");
    setBounds(100, 100, 450, 440);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);

    JLabel lblSumenRestaurant = new JLabel("Sumen Restaurant");
    lblSumenRestaurant.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblSumenRestaurant.setBounds(156, 11, 127, 29);
    add(lblSumenRestaurant);

    list = new JList(values);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    list.setBounds(115, 52, 200, 129);
    add(list);

    JLabel lblQuantity = new JLabel("Quantity");
    lblQuantity.setBounds(115, 225, 46, 14);
    add(lblQuantity);

    t1 = new JTextField();
    t1.setBounds(171, 222, 86, 20);
    add(t1);
    t1.setColumns(10);

    JButton b1 = new JButton("Calculate");
    b1.setBounds(171, 304, 89, 23);
    add(b1);

    b1.addActionListener(this);

}
    public void actionPerformed(ActionEvent e){





    }
}

2 个答案:

答案 0 :(得分:1)

代码现在有效!

设法使用list.isSelectedIndex()

答案 1 :(得分:-1)

你可以使用带有methode add的jlist项目

list = new JList(values); //没有使用eny更多,很快就会发现