Java actionPerformed无法正常工作

时间:2016-05-03 06:25:59

标签: java swing awt jbutton actionlistener

我试图用学校的GUI制作一个小型的二十一点游戏。这是代码:

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;

public class Gui extends JFrame implements ActionListener {

private JButton bBet;
private JLabel lblPointsPL;
private Blackjack bj;

public Gui() {

    Blackjack bj = new Blackjack();

    bBet = new JButton("Bet!");
    bBet.setBounds(10, 60, 200, 35);
    bBet.setForeground(Color.black);
    bBet.setBackground(Color.yellow);
    this.add(bBet);

    lblPointsPL = new JLabel("PointsPL");
    lblPointsPL.setBounds(300, 50, 200, 35);
    this.add(lblPointsPL);

    lblPointsPL.setText("test1");

}

public void actionPerformed(ActionEvent event) {

    Blackjack bj = new Blackjack();

    if (event.getSource() == bBet) {
        lblPointsPL.setText("test2");
    }

}

}

如果我按下bBet按钮,它应该将文本更改为" test2"但那不起作用。第一次更改为" test1"正在努力。

1 个答案:

答案 0 :(得分:3)

您忘记为按钮添加动作侦听器。

bBet = new JButton("Bet!");
bBet.setBounds(10, 60, 200, 35);
bBet.setForeground(Color.black);
bBet.setBackground(Color.yellow);
this.add(bBet);
bBet.addActionListener(this); // missing statement.