Advertisement
thenewboston

Java Programming Tutorial - 54 - Event Handler Program

Aug 22nd, 2014
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. import javax.swing.JFrame;
  2.  
  3. public class apples {
  4.    public static void main(String[] args){
  5.    
  6.       tuna bucky = new tuna();
  7.       bucky.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  8.       bucky.setSize(350, 100);
  9.       bucky.setVisible(true);
  10.    }
  11. }
  12.  
  13. import java.awt.FlowLayout;
  14. import java.awt.event.ActionListener;
  15. import java.awt.event.ActionEvent;
  16. import javax.swing.JFrame;
  17. import javax.swing.JTextField;
  18. import javax.swing.JPasswordField;
  19. import javax.swing.JOptionPane;
  20.  
  21. public class tuna extends JFrame{
  22.    
  23.    private JTextField item1;
  24.    private JTextField item2;
  25.    private JTextField item3;
  26.    private JPasswordField passwordField;
  27.    
  28.    public tuna(){
  29.       super("The title");
  30.       setLayout(new FlowLayout());
  31.      
  32.       item1 = new JTextField(10);
  33.       add(item1);
  34.      
  35.       item2 = new JTextField("enter text here");
  36.       add(item2);
  37.      
  38.       item3 = new JTextField("uneditable", 20);
  39.       item3.setEditable(false);
  40.       add(item3);
  41.      
  42.       passwordField = new JPasswordField("mypass");
  43.       add(passwordField);
  44.      
  45.       thehandler handler = new thehandler();
  46.      
  47.       item1.addActionListener(handler);
  48.       item2.addActionListener(handler);
  49.       item3.addActionListener(handler);
  50.       passwordField.addActionListener(handler);
  51.    }
  52.    
  53.    private class thehandler implements ActionListener{
  54.      
  55.       public void actionPerformed(ActionEvent event){
  56.          String string = "";
  57.          
  58.          if(event.getSource()==item1)
  59.                string=String.format("field 1: %s",event.getActionCommand());
  60.          else if (event.getSource()==item2)
  61.                string=String.format("field 2: %s",event.getActionCommand());
  62.          else if (event.getSource()==item3)
  63.                string=String.format("field 3: %s",event.getActionCommand());
  64.          else if (event.getSource()==passwordField)
  65.                string=String.format("password field is: %s",event.getActionCommand());
  66.          
  67.          JOptionPane.showMessageDialog(null, string);
  68.       }
  69.    }  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement