【问题标题】:How to change the text in a JButton如何更改 JButton 中的文本
【发布时间】:2014-09-02 12:58:34
【问题描述】:

是否可以在单击时更改 JButton 的文本? 我有一个 JButton,文本是一个数字,我希望当用户单击它时,按钮中的文本会增加。那可能吗?谢谢

【问题讨论】:

标签: jbutton


【解决方案1】:

您可以通过ActionEventgetSource() 方法访问单击的按钮。因此,您可以随心所欲地操作按钮。

试试这个:

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

【讨论】:

    【解决方案2】:

    另一种方法:

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

    【讨论】:

      【解决方案3】:

      这是我创建的解决方案。

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

      【讨论】:

        猜你喜欢
        • 2021-02-16
        • 1970-01-01
        • 1970-01-01
        • 2018-04-11
        • 2010-11-26
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多