import javax.swing.*; public class TextFieldExample { public static void main(String[] args) { JFrame frame = new JFrame("Text Field Example"); JTextField textField = new JTextField("Enter Your Name"); textField.setBounds(50,50,150,20); frame.add(textField); // set the focus to the text field textField.requestFocusInWindow(); frame.setSize(300,150); frame.setLayout(null); frame.setVisible(true); } }
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TextFieldExample2 implements ActionListener { JTextField textField1, textField2; JButton button; public TextFieldExample2() { JFrame frame = new JFrame("Text Field Example 2"); textField1 = new JTextField("Enter Number 1:"); textField1.setBounds(50,50,150,20); textField2 = new JTextField("Enter Number 2:"); textField2.setBounds(50,80,150,20); button = new JButton("Add"); button.setBounds(50,110,80,30); frame.add(textField1); frame.add(textField2); frame.add(button); // set the focus to the first text field textField1.requestFocusInWindow(); button.addActionListener(this); frame.setSize(300,200); frame.setLayout(null); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { int num1 = Integer.parseInt(textField1.getText()); int num2 = Integer.parseInt(textField2.getText()); int sum = num1 + num2; JOptionPane.showMessageDialog(null,"The sum is: "+ sum); } public static void main(String[] args) { new TextFieldExample2(); } }In this example, we create a JFrame, two JTextFields, and a JButton to perform an addition operation. The requestFocusInWindow() method is used to set the focus to the first text field when the application starts. When the user clicks on the button, the actionPerformed() method is called, which extracts the numbers from the text fields and performs the addition operation. The result is displayed using the JOptionPane.showMessageDialog() method. In both examples, the package library used is javax.swing.