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

How can I update the text of a JButton when I click on it?

我认为有比从 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();
            }
        });

这是我为 "refreshing" JButtons 编写的糟糕代码:

// 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() 为例。您显然会通过适用于您的程序的内容。