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

AWT List ft. ActionListener

Before seeing the inside of this post/article, it’s better you check on the previous post first which is Java AWT List. After you finish reading that one, you can comeback to this page. But hey… the choices are yours! so don’t mind it.

Okay, let’s just thought that you have known the basic of Java AWT List and now we’re going to add a few spice onto it which is ActionListener. We’re going to make the program outputs whatever objects we choose on the list by clicking an “output” button.

Let’s begin… The Exmpl !!! :
 *This Exmpl can be quit long because it involves ActionListener


//1st import  * we always uses JFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    

//2nd creates the object constructor and methods
    public class ListExmpl  extends JFrame
    {
         /**
         *
         */
        private static final long serialVersionUID = -5024249607576251689L;
        //for this time we’re going to try adding a serialVersionUID for the program       


        ListExmpl(){
            JFrame f= new JFrame(“List ft.ActionListener”);
            final Label label = new Label();        
            label.setAlignment(Label.CENTER);
            label.setSize(500,100);
            Button b=new Button(“Output!”);  //here we create the button
            b.setBounds(200,150,80,30);
            final List l1=new List(3, false);  //here we create the list
            l1.setBounds(100,100, 70,70);
            l1.add(“C”);
            l1.add(“C++”);
            l1.add(“Java”);
            final List l2=new List(3, true);
            l2.setBounds(100,200, 70,70);
            l2.add(“Turbo C++”);
            l2.add(“Spring”);
            l2.add(“Hibernate”);
            f.add(l1); f.add(l2); f.add(label); f.add(b);
            f.setSize(500,500);
            f.setLayout(null);
            f.setVisible(true);  

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            b.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {     
              String data = “Programming language Selected: “+l1.getItem(l1.getSelectedIndex());
              data += “, Framework Selected:”;
              for(String frame:l2.getSelectedItems()){
                       data += frame + ” “;
              }
              label.setText(data);
              }
             });        
    }  

//3rd call and run the objects
    public static void main(String args[])
    {
       new ListExmpl();
    }
    }  

This’ll output :

How To Create Button In JFrame

Okay, you’ll probably noticed in the title that today we’ll create somewhat a button program or application from scratch. Just like the other tutorial that I’ve  make this tutorial are going to use JFrame as its base. Let’s the code begin !


First of all like other program or application we should import any package or class that we know we would need, as long as the code being worked the import will increase one at a time, here are the first 3 imports :

import javax.*;
import java.awt.*;
import java.awt.event.*;

now let’s make the main class constructor :

public class Button { // well since we’re working with button
}

after that the most importan method of all, the public static void main method :

public static void main(String args){
}

Now the framework are done, we’ll get in bussiness with JFrame. Here we will write the base for our application which is the JFrame, oh yeah after this you need to import the JFrame
(import javax.swing.JFrame) :

      // creates a new JFrame named jframe titled Button (this could be titled anything else)
      JFrame jframe = new JFrame(“Button”); 
        // set the size of the jframe to be : width = 300 & height = 300;
        jframe.setSize(300, 300); 
        // set the visibility of the jframe to true, so it can be seen
        jframe.setVisible(true); 
        // set the jframe close operation
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE); 
       

And right now after you wrote all of those JFrame basic, you can run it and will see a frame of an application. But we’re not searching for not only application frame, we’ll make object inside it, in this case a button. So next we need to make a panel that would contain the button, and we’ll also import it
(import javax.swing.JPanel) :

       Panel panel = new JPanel(); // creates the JPanel
       jframe.add(panel); // we add the panel into the JFrame

And now the most anticipated part, we’ll create the button. Just as with JFrame and JPanel we’ll import JButton, and just like JFrame we’ll set the size and visibility, because you know if the visibility is false we won’t be able to see anything (import javax.swing.JButton) :

     // creates the button and set the title to be “Hello World” (you could name this anything else)
     JButton button = new JButton(“Hello World”); 
       // set the visibility of the button
       button.setVisible(true); 
       // set the size of the button
       button.setSize(100, 100);
       // we add the button to be contained by the panel
       panel.add(button); 
      

That’s it right now you just created a button, and this is all the code you’ve just wrotted :

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);
      
    }  
}

Not bad HUH!!, see you again the next time around. Happy Coding!.