gpt4 book ai didi

java - 单击 JButton 时如何更新它的文本?

转载 作者:行者123 更新时间:2023-12-02 05:01:24 26 4
gpt4 key购买 nike

我认为有比从 JPanel 中删除每个元素并重新制作它们更好的方法,因为这是我的解决方法,但现在显然当单击按钮时它被告知删除自身,因此操作永远不会完成。

这是我添加按钮操作监听器的糟糕代码:

// Add action listener to increment quest progress when button is pushed
listOfButtons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
questList[temp].incrementNumerator(1);
refreshButtons();
}
});

这是我“刷新”JButton 的糟糕代码:

// Use when updating data that a JButton displays, destroys & recreates all     JButtons on the window
private void refreshButtons() {
for (int i = 0; i < listOfButtons.length; i++) {

// Remove each JButtons from the JFrame
contentPane.remove(listOfButtons[i]);
}
addButtons();
}

最佳答案

您可以从 ActionEvent 本身获取 JButton 引用。

listOfButtons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
questList[temp].incrementNumerator(1);
((JButton) e.getSource()).setText(questList[temp].getValue());
}
});

我使用了 questList[temp].getValue() 作为示例。显然,您将通过对您的程序有效的方法。

关于java - 单击 JButton 时如何更新它的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28261495/

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