桂按钮不起作用

时间:2015-12-28 15:51:15

标签: java user-interface

我是新来的,对不起,如果有点难以理解。基本上我的问题是我必须制作一个GUI Hangman游戏,我现在正试图让猜测按钮工作,但它似乎并不是它想要的。

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.MatteBorder;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;

public class Hangman2 {

  static final int maxguess = 8;
  static final int maxletter = 'z' - 'a' + 1;
  private JFrame frame;
  private JTextField textField;
  public int guess;

  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
          Hangman2 window = new Hangman2();
          window.frame.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }

  /**
   * Create the application.
   */
  public Hangman2() {
    initialize();
  }

  /**
   * Initialize the contents of the frame.
   */
  private void initialize() {

    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 450, 206);
    panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
    frame.getContentPane().add(panel);

    textField = new JTextField();
    textField.setBounds(10, 211, 113, 26);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    JButton btnGuess = new JButton("Guess");
    frame.getContentPane().add(btnGuess);
    btnGuess.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        guess++;
      }
    });
    btnGuess.setBounds(6, 243, 125, 29);
    frame.getContentPane().add(btnGuess);

    int guesses = (guess);

    JLabel lblNumberOfGuesses = new JLabel("Number of guesses:" + guesses);
    lblNumberOfGuesses.setBounds(135, 216, 155, 16);
    frame.getContentPane().add(lblNumberOfGuesses);
  }
}

1 个答案:

答案 0 :(得分:1)

JLabel方法中initialize的文字仅设置一次

在增加猜测后,在actionPerformed方法中执行此操作:

public void actionPerformed(ActionEvent e) {
        guess++;
        lblNumberOfGuesses.setText("Number of guesses:" + guess);
      }

另外,在声明ActionListener之前声明你的JLabel ,否则你会有错误,因为在这一步中lblNumberOfGuesses将是未知的。