简体   繁体   中英

why doesnt my actionListener work with my jcomboBox

I know I'm missing something very simplem but for the life of me I can't see it. All I want to do is get "Paris" from the combo box, and when the button is pressed, show that "Paris" is selected.

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");
                }
            }
        });
    }
}

EDIT: I just now noticed that your class implements ActionListener . With the below solution, you can remove the implements -statement from your code.

To fix your issues with the String having to be final, make a private class:

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

Then, replace

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

with

PriceCheck.addActionListener(new MyListener());

This should be able to print out the selected value after the button is pressed.

Note: I changed your variable name from LocationBox to locationBox to comply with naming conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM