-1

我对以下代码有疑问。ActionEventListener 似乎没有正确遵循我的“if”语句。编译后,无论我按下哪个按钮,它都会执行以下 if 语句,就好像按下了“购买”按钮一样。在我进行购买操作之前,它正在退出。如果我按下“帮助”按钮,它首先会出现相应的消息,但是一旦点击确定,那么程序就好像程序然后自动点击“购买”按钮,然后立即退出按钮

我确实使用 If else 语句尝试过这个,但是我收到错误消息“'else' without '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);
            }
        }
4

2 回答 2

0

I do it in this way:

Adding ActionListener to JButton:

jbutton.addActionListener(this);

Setting ActionCommand to JButton:

jbutton.setActionCommand("jbutton1");

actionperformed method:

public void actionPerformed(ActionEvent e){
    if(e.getActionCommand.equals("jbutton1"){
       .....
    }
}
于 2013-11-04T14:31:58.353 回答
0

使用Object'sequals()方法,而不是==运算符,它只比较对象引用。

于 2013-11-04T14:30:42.627 回答