[英]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.
我要做的就是从组合框中获取“ Paris”,并在按下按钮时显示已选择“ Paris”。
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
. 编辑:我刚才注意到您的类
implements ActionListener
。 With the below solution, you can remove the implements
-statement from your code. 随着下面的解决方案,你可以删除
implements
从您的代码语句来。
To fix your issues with the String having to be final, make a private class: 要解决String必须是final的问题,请创建一个私有类:
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. 注意:我将变量名从
LocationBox
更改为locationBox
以符合命名约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.