Java programming part 68 GUI : ToolBars Fired event in ActionPerformed, using the Object class
Channel: Redemptie
Date: 23/05/2012

Java Programming tutorial, GUI, Graphical User Interface. this tutorial is teaching How to use one actionListener for many different events and object by using the Object class and getSource() method fron ActionEvent. Also implementing toolbar in a borderLayout panel.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class UserFrame extends JFrame implements ActionListener{
 public static String name = "charles";
 public static JMenuItem print;
 public static JButton jb11;
 UserFrame(){
  setTitle("UsersFrame");
  setSize(600,550);
   
 }


public static void main(String[] args){
 
 UserFrame f = new UserFrame();
 JMenuBar bar = new JMenuBar();
 bar.setToolTipText("this is the manu bar please use this carefully");
 JToolBar tb = new JToolBar();
 tb.setToolTipText("This is a too bar");
 jb11 = new JButton("tb11");
 jb11.addActionListener(f);
 jb11.setToolTipText("this button has a tool tip, please read!");
 JButton jb12 = new JButton("tb12");
 JButton jb13 = new JButton("tb13");
 JButton jb14 = new JButton("tb14");
 JButton jb15 = new JButton("tb15");
 JButton jb16 = new JButton("tb16");
 JButton jb17 = new JButton("tb17");
 JMenu fileMenu = new JMenu("File");
 JMenu editMenu = new JMenu("Edit");
 print = new JMenuItem("print name");
 JMenuItem print2 = new JMenuItem("print nothen");
 print.addActionListener(f);
 fileMenu.add(print);
 fileMenu.add(print2);
 bar.add(fileMenu);
 bar.add(editMenu);
 f.setJMenuBar(bar);
 

 tb.add(jb11);
 tb.add(jb12);
 tb.add(jb13);
 tb.add(jb14);
 tb.add(jb15);
 tb.add(jb16);
 tb.add(jb17);

 JPanel pan = new JPanel();
 pan.setLayout(new BorderLayout());
 pan.add(tb);
 f.add(pan);
 f.setDefaultCloseOperation(EXIT_ON_CLOSE);
 f.setVisible(true);
}


@Override
public void actionPerformed(ActionEvent e) {
 // TODO Auto-generated method stub
 
 Object c = (Object) e.getSource();

 if(c==jb11){
  System.out.println("Charles");
 }
 if(c==print){
  System.out.println("Menu Item Fire Event");
 }

}


}