我遇到以下代码的问题。 ActionEventListener似乎没有正确地遵循我的“if”语句。编译时,无论我按哪个按钮,它都会执行以下if语句,就像按下“Purchase”按钮一样。在我进行购买操作之前,它已经放弃了。如果我按下“帮助”按钮,它会首先显示相应的消息,但是一旦确定被点击,那么程序就好像程序然后自动点击“购买”按钮,然后立即退出按钮
我确实尝试使用If else语句,但是当时我收到错误消息“'else'没有'if'”
任何帮助将不胜感激。
public class Gui extends JFrame {
private JButton purchaseSeats, selectSeats, helpInfo, viewReciept, quit;
public Gui(){
super ("Cinema Seat Booking and Selection Program");
setLayout(new FlowLayout());
purchaseSeats = new JButton("Purchase Seats");
selectSeats = new JButton("Select Seats");
helpInfo = new JButton("Help");
viewReciept = new JButton("Reciept");
quit = new JButton("Quit");
//add buttons to GUI
add(purchaseSeats);
add(selectSeats);
add(helpInfo);
add(viewReciept);
add(quit);
//tool tips
purchaseSeats.setToolTipText("Purchase randomly allocated seating");
selectSeats.setToolTipText("Select specific seats for purchasing");
helpInfo.setToolTipText("Instruction on how to use the Cinema Seat "
+ "Booking and Selection Program");
viewReciept.setToolTipText("View the reciept for all the seats you have"
+ " purchased");
quit.setToolTipText("Exit the program");
//action listeners
purchaseSeats.addActionListener(new ButtonListener());
selectSeats.addActionListener(new ButtonListener());
helpInfo.addActionListener(new ButtonListener());
viewReciept.addActionListener(new ButtonListener());
quit.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent event)
{
if(event.getSource()==helpInfo){
JOptionPane.showMessageDialog(null, "Help Menu"
}
if (event.getSource()==purchaseSeats);
{
//insert instructions for purchasing seats
}
if (event.getSource()==selectSeats);
{
//insert instructions for purchasing seats
}
if (event.getSource()==viewReciept);
{
//insert instructions for purchasing seats
}
if (event.getSource()==quit);
{
System.exit(0);
}
}
答案 0 :(得分:0)
使用Object
的{{1}}方法,而不是equals()
运算符,它只比较对象引用。
答案 1 :(得分:0)
我是这样做的:
将ActionListener添加到JButton:
jbutton.addActionListener(this);
将ActionCommand设置为JButton:
jbutton.setActionCommand("jbutton1");
actionperformed方法:
public void actionPerformed(ActionEvent e){
if(e.getActionCommand.equals("jbutton1"){
.....
}
}