2013-02-11 106 views
1

單擊時是否可以更改JButton的文本? 我有一個JButton,文本是一個數字,我想要發生的是當用戶點擊它時,按鈕中的文本將增加。那可能嗎?謝謝如何更改JButton中的文本

+0

告訴我們你試過了什麼? – ogzd 2013-02-11 13:44:27

+0

可能重複:** [單擊時更改JButton文本](http://stackoverflow.com/questions/9412620/changing-a-jbutton-text-when-clicked)** – 2013-02-11 13:49:41

回答

1

您可以通過getSource()方法ActionEvent訪問點擊按鈕。因此,您可以儘可能多地操作按鈕。

試試這個:

@Override 
public void actionPerformed(ActionEvent e) { 
    JButton clickedButton = (JButton) e.getSource(); 
    clickedButton.setText("Anything you want"); 
} 
0

另一種方式來做到這一點:

JButton button = new JButton("1"); 
button.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    int count = Integer.parseInt(button.getLabel()); 
    button.setLabel((String)count); 
    } 
}); 
0

這是我創建了一個解決方案。

public int number = 1; 
public Test() { 
    final JButton test = new JButton(Integer.toString(number)); 
    test.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
      number += 1; //add the increment 
      test.setText(Integer.toString(number)); 
     } 
    }); 
} 

首先,創建一個整數。然後,由於JButton的文本只能是一個字符串,所以創建的JButton的整數值轉換爲一個字符串。接下來,使用內部類,爲該按鈕創建一個動作偵聽器。當按下按鈕時,會執行以下代碼,使整數的值遞增,並將按鈕的文本設置爲轉換爲字符串的整數值。