I just recently got into coding and running applications using Java's Swing. While trying to get Event Handling and ActionListeners and whatnot to work, I ran into a problem and I cannot for the life of me figure it out. I was following TheNewBoston's video tutorial, and I went back and checked my code multiple times, and the process that I follow is exactly the same as his, but his ran and worked while mine ran but did not function properly. Was wondering if anybody could look over it and tell me what's wrong with it. Thanks!
EventHandlerMain Source Code:
import javax.swing.*; import java.awt.*; class EventHandlerMain { public static void main(String[] Args) { EventHandlerSecondary gui = new EventHandlerSecondary(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setSize(350,150); gui.setVisible(true); } }
EventHandlerSecondary Source Code:
import javax.swing.*; import java.awt.*; public class EventHandlerSecondary extends JFrame { private JTextField tf1; private JTextField tf2; private JTextField tf3; private JPasswordField pwf; public EventHandlerSecondary() { super("Event Handling Test"); setLayout(new FlowLayout()); tf1 = new JTextField(10); add(tf1); tf2 = new JTextField("Enter Text Here..."); add(tf2); tf3 = new JTextField("* Not Available *", 20); add(tf3); tf3.setEditable(false); pwf = new JPasswordField("password"); add(pwf); Handler eventHandler = new Handler(); tf1.addActionListener(eventHandler); tf2.addActionListener(eventHandler); tf3.addActionListener(eventHandler); pwf.addActionListener(eventHandler); } private class Handler implements ActionListener { public void actionPerformed(ActionEvent event) { String string = ""; if(event.getSource() == tf1) string = String.format("Field 1: %s", event.getActionCommand)); else if(event.getSource() == tf2) string = String.format("Field 2: %s", event.getActionCommand)); else if(event.getSource() == tf3) string = String.format("Field 3: %s", event.getActionCommand)); else if(event.getSource() == pwf) string = String.format("Password field is: %s", event.getActionCommand)); JOptionPane.showMessageDialog(null, string); } } }