Sunday 16 October 2016

JButton


   JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with the push button. 
     Three of its constructors are: 
JButton(Icon icon) 
JButton(String str) 
JButton(String str, Icon icon) 
Here, str and icon are the string and icon used for the button.      When a button is pressed, an ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed() method of registered ActionListener, we can obtain the action command string associated with the button. By default, this is the string displayed inside the button. 
 We can set the action command by calling setActionCommand() on the button. We can obtain the action command by calling getActionCommand() on the event object. 
      Example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyButton extends JApplet {
  JLabel l1;
  public void init()  {
   try  {
    SwingUtilities.invokeAndWait(new Runnable() {
      public void run()   {
          makeGUI();
      }
    });
  } catch(Exception e){
           System.out.println("Sorry some error occured "+e);
        }
 }
 private void makeGUI() {
   setLayout(new FlowLayout());
   ImageIcon ic1=new ImageIcon("icon1.png");
   JButton b1=new JButton(ic1);
   b1.setActionCommand("Icon1");
   b1.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent ae){  
      l1.setText("You selected "+ ae.getActionCommand());
    }
   });
   add(b1);
   b1=new JButton("Icon2");
   b1.setActionCommand("Icon2");
   b1.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent ae){  
      l1.setText("You selected "+ ae.getActionCommand());
     }
    });
   add(b1);
   l1=new JLabel("Chose an Icon");
   add(l1);
 }
}

Output:

No comments:
Write comments