JButton with ActionListener (Count!!!)

How is it going everybody? Pheww… Its been quite too long since my last article Ha! Now I’m back in shape with another new article. Today’s article is about a Button, well I’m feeling a little bit itchy about Button because I hasn’t made an interactive button (ActionListener). So today’s all about adding an ActionListener to a Button.

Okay so if you doesn’t know how to create a Button in Java, check out This article on how to create Button in Java : Button 

This is the code of a JButton :

 import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;

public class Button {
    public static void main(String args[]){
        JFrame jframe = new JFrame(“Button”);
        jframe.setSize(300, 300);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
      
        JPanel panel = new JPanel();
        jframe.add(panel);
        JButton button = new JButton(“Hello World”);
        button.setVisible(true);
        button.setSize(100, 100);
        panel.add(button);
      
    }  
}

First here is the code that implements ActionListener :

button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) { 
      
      for(int i = 0; i < 20; i++){
       int s = 5;

       while(s < 20) {
         s++;
         System.out.println(s);
           }    
       }     
    }
}

That’s it, now you just need to implement it to your original Button code :


 import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;

public class Button {

    public static void main(String args[]){
        JFrame jframe = new JFrame(“Button”);
        jframe.setSize(300, 300);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
      
        JPanel panel = new JPanel();
        jframe.add(panel);
        JButton button = new JButton(“Hello World”);
        button.setVisible(true);
        button.setSize(100, 100);
        panel.add(button);

        button.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) { 
      
      for(int i = 0; i < 20; i++){
       int s = 5;
       while(s < 20) {
         s++;
         System.out.println(s);
           }    
       }     
    }
}
      
    }  
}


That is a button that will count (increments (++) ) the number 5 by 1 and would go on while the number is still smaller (<) than 20.



How to add Sound / Music in Java Program

How is it going coders? for today specials… I’m goinna tell you on how to add sound or music into Java Program. For todays example I’m using Eclipse, you could use it or any other IDE that suites you. First of all the sound file I’m using is a wav format, keep that in mind.

Okay so first of all you need to have is a sound file, and you need to put it inside the project folder as shown below :

So I have a sound file named “arrow” inside my project folder named “BackGroundSound”.
After that, we’ll just have to do a little bit of coding :


//1st now well import the important classes 
//(notice that there is a class/package named sun.audio)
import sun.audio.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;

import javax.swing.*;

//2nd we create our method inside our class

public class BackSound extends JFrame{

//here we create the main method

    public static void main(String[] args){
      JFrame frame = new JFrame(“BackSound”);   
      frame.setSize(300, 300);
      JButton button = new JButton(“Turn On Sound”); //we create the buttons to click
      frame.add(button);
      button.addActionListener(new AL());
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    }
   
    public static class AL implements ActionListener{
        public final void actionPerformed(ActionEvent e){
        //here we creates a method AL that implements ActionListener for the button
            music();
        }}
   
    public static void music(){
        AudioPlayer MGP = AudioPlayer.player; //here we create an AudioPlayer from sun.audio
        AudioStream BGM; //here we create an AudioStream from sun.audio
        AudioData MD; //here we create an AudioData from sun.audio
       
        ContinuousAudioDataStream loop = null;
        //here we loop our audio inside the program
       
        try{
        BGM = new AudioStream(new FileInputStream(“arrow.wav”)); //here we find our sound file
        MD = BGM.getData();
        loop = new ContinuousAudioDataStream(MD);
        }catch(IOException error){//here we catch an IOException, if it occurs it will print “yo”
            System.out.println(“yo”);
        }
       
        MGP.start(loop); //here we’ll start the loop whenever the method “music” is called
    }
}

Well since I can’t tell you how it sounds in here, you can go and check my Youtube Channel for the Voice explanation : How to add Sound / Music in Java Program (Eclipse) Check it out!! and subscribe

Java Event Handling

Java Event Handling or Event Listener is a way that programmer use to listen or handle an event,what is an event you might ask, an event means that we’re changing the state of an object to another form. For example, dragging mouse, clicking a button etc. The packages that provides many-many listener interface and event classes for event handling is a job for java.awt.event package.

Here is list of the event classes and listener that java.awt.event have :

  • ActionEvent  :  ActionListener
  • KeyEvent  :  KeyListener
  • MouseEvent :   MouseListener and MouseMotionListener
  • MouseWheelEvent  :  MouseWheelListener
  • TextEvent  :  TextListener
  • ItemEvent  :  ItemListener
  • WindowEvent  :  WindowListener
  • ComponentEvent  :  ComponentListener
  • ContainerEvent  :  ContainerListener
  • AdjustmentEvent  :  AdjustmentListener
  • FocusEvent :  FocusListener

First before you can do some badass event handling, you need to know the basic steps of event handling :

  1. First, implements the Listener interface and override its methods.
  2. Second, register the component with the Listener.

Here the is some classes that provides registration methods :

  • Button : public void addActionListener(ActionListener a){}
  • TextArea : public void addTextListener(TextListener a){}
  • TextField : public void addActionListener(ActionListener a){}
                     public void addTextListener(TextListener a){}
  • List : public void addActionListener(ActionListener a){}
            public void addItemListener(ItemListener a){}
  • Checkbox : public void addItemListener(ItemListener a){}
  • Choice: public void addItemListener(ItemListener a){}

After you know the steps and you also know registration methods looks like, you need to know where you should place or put you event handler, and here are 3 place :

  1. Same class
  2. Other class
  3. Annonymous class

Okay, now you know the basics of event handling, I think we’re good to go to an example, and so… here it is :

    import java.awt.*;  //imports the java.awt package
    import java.awt.event.*;  //import the java.awt.event package
     
    public class EventHandling extends Frame implements ActionListener{  

         //class extends Frame and implements ActionListener
        private static final long serialVersionUID = 1L;
    TextField tf;  //create a textfield
    EventHandling(){  //create the constructor
     
    tf=new TextField();  //creates a new TextField tf
    tf.setBounds(60,50,170,20);  //set the size and boundaries
     
    Button b=new Button(“Greetings”);  // creates a button displaying String “Greetings”
    b.setBounds(100,120,80,30);  //set the size and boundaries
     
    b.addActionListener(this);  //add an ActionListener to Button b.
     
    add(b);add(tf);  //add TextField tf to Button b.
   
   
    setSize(300,300);  //set the size of the Frame
    setLayout(null);  //set the layout to null
    setVisible(true);  //set the visibility to true.
     
    } 
     
    public void actionPerformed(ActionEvent e){ 
    tf.setText(“Welcome”);  

//creates an actionPerformed event, so when the button is clicked it will output “Welcome”
    } 
     
    public static void main(String args[]){ 
    new EventHandling();  //finally run everything by calling EventHandling() method.
    } 
    }   

The result is this :

Button and Textfield ActionListener and actionPerformed
Button and Texfield ActionListener and actionPerformed

 Conclusions

  • Java Event Handling or Event Listener is a way that programmer use to listen or handle an event.
  • An event means that we’re changing the state of an object to another form. For example, dragging mouse, clicking a button etc.
  • The packages that provides many-many listener interface and event classes for event handling is a job for java.awt.event package.