GUI WITH JFRAME; ACTION LISTENER & EVENT HANDLER
import javax.swing.*;
class First{
public static void main(String args[]) {
// Creating an object for the Second class
Second secondObject = new Second();
// when hitting the X button the window will close
secondObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// setting the size of the window
secondObject.setSize(350, 100);
// setting the visibility of the window
secondObject.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
// Inheriting JFrame methods
public class Second extends JFrame{
// creating Textfield variables
private JTextField item1, item2, item3;
// creating password variable
private JPasswordField passwordField;
// making a constructor for the GUI
public Second(){
// setting the title
super("Title");
setLayout(new FlowLayout());
// variable assigned to a textfield
item1 = new JTextField(10);
// adding the variable
add(item1);
// variable assigned to a textfield with default text in it
item2 = new JTextField("Enter Text Here");
// adding the variable
add(item2);
// variable assigned to textfield with default text in it
item3 = new JTextField("Uneditable", 20);
// making the textfield uneditable
item3.setEditable(false);
// adding the variable
add(item3);
// variable assigned to password with default password in it
passwordField = new JPasswordField("mypass");
// adding the variable
add(passwordField);
// Creating an object because .addActionListener only takes on object as its argument
thehandler handler = new thehandler();
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
passwordField.addActionListener(handler);
}
// Creating the event handling class which implements ActionListener
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
// checking if the source of the event is one of the variables and giving an output for each of them
if (event.getSource() == item1){
string = String.format("Field 1: %s", event.getActionCommand());
} else if (event.getSource() == item2){
string = String.format("Field 2: %s", event.getActionCommand());
} else if(event.getSource() == item3){
string = String.format("Field 3: %s", event.getActionCommand());
} else if(event.getSource() == passwordField){
string = String.format("Password field is: %s", event.getActionCommand());
}
// positioning the message dialog in the center of the screen and showing the string
JOptionPane.showMessageDialog(null, string);
}
}
}