Java Swing Program to demonstrate JButton Action TextField
Program
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.event.*;
public class JButtonActionTextBox{
public static void main(String[] args) {
JFrame frm = new JFrame("JButton Action Listener");
JPanel pnl = new JPanel();
JTextField txtDisplay = new JTextField(20);
txtDisplay.setBounds(50, 50, 150, 20);
JButton btnSubmit = new JButton("Click Here");
btnSubmit.setBounds(50, 200, 100, 20);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtDisplay.setText("Welcome to www.oodlescoop.com");
}
});
pnl.add(txtDisplay);
pnl.add(btnSubmit);
frm.add(pnl);
frm.setSize(300, 300);
frm.setVisible(true);
frm.setLayout(null);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This Java Swing program demonstrates the use of a JButton with an ActionListener to perform an action on a JTextField. Here's a brief explanation:
-
JFrame Setup:
- A
JFramenamedfrmis created with the title "JButton Action Listener." - The
JFrameis set to close the application when the window is closed usingsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
- A
-
JPanel:
- A
JPanelnamedpnlis added to the frame to hold the components.
- A
-
JTextField:
- A
JTextFieldnamedtxtDisplayis created with a width of 20 columns for text input/display. - Its bounds are set using
setBounds, though this is unnecessary since the program usesJPanel(which uses a default layout manager).
- A
-
JButton:
- A
JButtonnamedbtnSubmitis created with the label "Click Here." - An
ActionListeneris added to the button usingaddActionListener. When the button is clicked, thetxtDisplaytext is updated to display the message "Welcome to www.oodlescoop.com".
- A
-
Adding Components:
- Both the
txtDisplayandbtnSubmitcomponents are added to theJPanel. - The
JPanelis then added to theJFrame.
- Both the
-
Display Settings:
- The
JFramesize is set to300x300. - The
JFrameis made visible withsetVisible(true).
- The
Output