How can we change the JButton text dynamically in Java?


A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate the MouseListener and KeyListener interfaces. By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.getText()) method of a JButton class.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonTextChangeTest extends JFrame {
   private JTextField textField;
   private JButton button;
   public JButtonTextChangeTest() {
      setTitle("JButtonTextChange Test");
      setLayout(new FlowLayout());
      textField = new JTextField(20);
      button = new JButton("Initial Button");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            if (!textField.getText().equals(""))
               button.setText(textField.getText());
         }
      });
      add(textField);
      add(button);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JButtonTextChangeTest();
   }
}

Output

Updated on: 10-Feb-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements