Pages

Thursday, September 8, 2016

add action listener to java buttons

Explanation

If you will create a button in java so you have to add an action to the button.(action) means if someone click the button you added to the java JPanel/JFrame/canvas/applet So you want that it should to open something with it. below is the source so get them and copy them to the eclipse and practice hard to get the idea
myClass = sorce code of myClass

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 = source code of myMain
package myPackage;

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


If right now if you have any problem about java programming just contact me throw i have given the contact form in each of my page.So just click on that and leave me a comment or just message me and trust me.i'd love help you out from every difficulties you have..

No comments:

Post a Comment