【问题标题】:How can I update the text of a JButton when I click on it?单击 JButton 时如何更新它的文本?
【发布时间】:2015-03-31 10:33:52
【问题描述】:

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

这是我用于“刷新” 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();
}

【问题讨论】:

    标签: java swing refresh jbutton jlabel


    【解决方案1】:

    您可以从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() 为例。您显然会通过对您的程序有效的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 2014-11-30
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多