2013-02-11 101 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的整数值转换为一个字符串。接下来,使用内部类,为该按钮创建一个动作侦听器。当按下按钮时,会执行以下代码,使整数的值递增,并将按钮的文本设置为转换为字符串的整数值。