如何更改JButton中的文本

时间:2013-02-11 13:43:58

标签: jbutton

单击时是否可以更改JButton的文本? 我有一个JButton,文本是一个数字,我想要发生的是当用户点击它时,按钮中的文本将递增。那可能吗?感谢

3 个答案:

答案 0 :(得分:1)

您可以getSource() ActionEvent方法访问点击的按钮。因此,您可以根据需要操作按钮。

试试这个:

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

答案 1 :(得分: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);
  }
});

答案 2 :(得分: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的文本只能是一个字符串。接下来,使用内部类,为按钮创建一个动作侦听器。按下该按钮时,将执行以下代码,该代码递增整数的值,并将按钮的文本设置为强制转换为字符串的整数值。