Pages

Monday, November 9, 2015

how to add an action to a button in java

Source code for the button actionListener




myClass= code below





package myPackage;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class myClass extends JFrame {
   
  /*create JPanel*/
   JPanel panel = new JPanel();
   
   /*create JButton here*/ 
 JButton button =new JButton("Click me");


 public myClass(){
   setSize(400,600);
   setDefaultCloseOperation
   (JFrame.EXIT_ON_CLOSE);
     setVisible(true);
   setTitle("simple Button");
   add(panel);
   button.setPreferredSize(new Dimension(100,50));
   panel.add(button);

   /*add Action Listener*/
   button.addActionListener(new ActionListener(){
   
public void actionPerformed(ActionEvent e) {
  /*asign source in an object*/           

  Object source = e.getSource();
   /*add action*/
  if(source==button){
            
 /*print text to the console*/
System.out.println("i am clicked");

  }  
  }
       
       
   });

 } 
 
   
}






myMain = main class source code below

 package myPackage;

  public class  myMain  {
     
     
         public static void main(String[]args){
           myClass cl= new myClass();


         }
    }





No comments:

Post a Comment