- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to change JButton font dynamically in Java?
- How can we implement the HTML text of JButton in Java?
- How can we set the margin to a JButton in Java?
- How can we apply different borders to JButton in Java?
- How can we set the shortcut key to a JButton in Java?
- How can we add/insert a JButton to JTable cell in Java?
- How can we rotate a JLabel text in Java?
- How we can instantiate different python classes dynamically?
- How can we call the invokeLater() method in Java?\n
- How can we align the JRadioButtons horizontally in Java?\n
- How can we sort a JSONObject in Java?\n
- Can we change the Cursor with Java Swing?
- How can we change the default font of the JTabbedPane tabs in Java?
- Can we change method signature in overriding in Java?
- How can we create a login form in Java?\n

Advertisements