gpt4 book ai didi

java - Gui 按钮不起作用

转载 作者:行者123 更新时间:2023-12-01 10:39:31 26 4
gpt4 key购买 nike

我是新来的,如果有点难以理解,很抱歉。基本上我的问题是我必须制作一个 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);
}
}

最佳答案

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

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

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

此外,在声明 ActionListener 之前声明您的 JLabel,否则您将会出错,因为在此步骤中 lblNumberOfGuesses 是未知的。

关于java - Gui 按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com