为什么我的actionListener不能使用我的jcomboBox

时间:2015-05-02 23:05:04

标签: java swing

我知道我错过了一些非常简单的东西,但对于我的生活,我看不到它。我想要做的就是从组合框中获取“巴黎”,当按下按钮时,显示选择了“巴黎”。

public class assignment2try2 implements ActionListener {
    private JComboBox HolidayLocation;  
    private JComboBox HolidayDuration;
    private JButton PriceCheck; 

    public static void main(String[] args) {        
        JLabel Location = new JLabel(" Where do you want to go ? ");

        String[] HolidayLocations = {" ","Paris", "Crete", "Croatia"};
        JComboBox<String> LocationBox = new JComboBox<String>(HolidayLocations);
        LocationBox.setEditable(false);
        LocationBox.setPreferredSize(new Dimension( 160, 20 ));
        //LocationBox.setSelectedIndex(4);
        LocationBox.addActionListener(LocationBox);

        JButton PriceCheck = new JButton("Check Availability");
        PriceCheck.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("button works");
                //if(LocationBox.getSelectedItem().equals(HolidayLocations))
                {
                    //System.out.println("paris selected");
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

编辑:我刚才注意到你的班级implements ActionListener。使用以下解决方案,您可以从 代码中删除implements - 语句。

要修复String必须是final的问题,请创建一个私有类:

private class MyListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println(locationBox.getSelectedItem() + " selected.");
    }
}

然后,替换

PriceCheck.addActionListener(new ActionListener() { ... });

PriceCheck.addActionListener(new MyListener());

按下按钮后,应该可以打印出所选的值。

注意:我将变量名称从LocationBox更改为locationBox,以符合命名约定。