How To Play MP3 Files in Java Eclipse

How is it going coders? for today Tutor… I’m gonna tell y’all how to Play MP3 files in Java Program. Just like always for todays example I’m using Eclipse, you could use it or any other IDE that suites you. For todays program I’m using MP3 files, so thats not too hard to find.

 First of all you need to have your MP3 files inside your source folder like this :

Just look at that “Mfg” MP3 files that I have inside my source folder for “MainMP3” Program.
Now for the coding Spices :


Wait!!! Before all of that You need to Download JLayer Here :  JLayer
And add it to your program Build Path using “Add External JARs” :

//1st now well import the important classes
//(notice that there is a class/package named javazoom.jl…)

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

//2nd we create our method inside our class
public class MainMP2 {
 

//here we create the main method

    public static void main(String[] args){
       
        try{
        FileInputStream fileInputStream = new FileInputStream(“Mfg.mp3”);
 //here we find our sound file
        Player player = new Player(fileInputStream);
        player.play();
        System.out.println(“Song is Playing”);
        } catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(JavaLayerException e){
            e.printStackTrace();
        }
       
    }
   
}

Well since I can’t tell you how it sounds in here, you can go and check my Youtube Channel for the Voice explanation : MP3 Files in Java Eclipse Check it out!! and subscribe

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

Canvas for Drawing (Java AWT)

A Canvas in Java (specifically AWT class) is a black rectangular / rectangle area where the application itself can draw or trap an input events from the user. The canvas inherits Component class.

AWT Canvas Syntax

public class Canvas extends Component implements Accessible  

No more chit-chatting, here’s an example of what you can do in AWT Canvas :

//1st import
  import java.awt.*;

 //2nd creates the method

 import javax.swing.JFrame;
public class CanvasExmpl extends JFrame
{
public CanvasExmpl()
{
JFrame f= new JFrame(“Canvas Example”);
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(300, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}



//3rd call and run it!     

public static void main(String args[]) {
new CanvasExmpl();
}
}
class MyCanvases extends Canvas
{
public MyCanvases() {
setBackground (Color.BLACK);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
g.fillOval(75, 75, 150, 75);
}
}

 

Watch my Youtube video on the same topic : https://www.youtube.com/watch?v=risnqJoa8uI

Toolkit : How to change TitleBar Icon

Okay, from the last post we learn about Toolkit and how to use them. Today we’ll make an implementation of it, today we’ll learn how to change a TitleBar Icon.

Let’s get right to Exmpl !

    import java.awt.*;
    import javax.swing.JFrame;   


    class ToolkitExmpl extends JFrame{  
    ToolkitExmpl(){  
    JFrame f=new JFrame();  
    Image icon = Toolkit.getDefaultToolkit().getImage(“C:\Users\Craftingez6\Pictures\IP.jpg”);

    /*png or jpg it depends on the Image you’re using */
    f.setIconImage(icon); 
    f.setLayout(null);  
    f.setSize(500,500);  
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }  
    public static void main(String args[]){  
    new ToolkitExmpl();  
    }  
    }  

This’ll output :

Making a Dialog (Application) in Java

Dialog in English  is “A conversation between two or more people as a feature of a book, play, or film. ‘the book consisted of a series of dialogues’(Quoted from Oxford Dictionaries), whereas in Java it represent a window with a border, titles that’s used to take somekind of input form from the user. Dialog inherits the Window class. Basically it’s like Frame, but there’s a difference, when Frame have minimize and maximize button whereas Dialog only have a close button..

In below you can see the declaration of Dialog class. 
 
public class Dialog extends Window  

Nevertheless… It’s Exmpl time! :

//1st import
    import java.awt.*; 
    import java.awt.event.*;
    import javax.swing.JFrame; 
//2nd Create the Object constructor and method
    public class DialogExmpl extends JFrame{ 
        private static Dialog d; 
        DialogExmpl() { 
            JFrame f= new JFrame(); 
            d = new Dialog(f , “Dialog Exmpl”, true);  //here we create the Dialog
            d.setLayout( new FlowLayout() ); 
            Button b = new Button (“OK”);  //here we create the Button
            b.addActionListener ( new ActionListener() 
            { 
                public void actionPerformed( ActionEvent e )  //here we create the ActionPerformed
                { 
                    DialogExmpl.d.setVisible(false); 
                } 
            }); 
            d.add( new Label (“Click button to continue. (Closes this)”)); 
            d.add(b);  
            d.setSize(300,300);   
            d.setVisible(true);
        }  

//3rd call and run the Object constructor and method
        public static void main(String args[]) 
        { 
            new DialogExmpl(); 
        } 
    }  

This’ll output this : 


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 :

Check The Box Boy! (Java CheckBox)

Checkbox class in java is used to, you know… create a checkbox. Check box basically is used to turn 1 or more option to true (on) or false (off). Clicking for either one of the checkbox changes the state of one of the option from “off” to “on” or from “on” to “Off”.

before we began, you need to know the class declaration :
  
public class Checkbox extends Component implements ItemSelectable

Let’s began, Exmpl time! :

 //1st import it

    import java.awt.*;
    import javax.swing.JFrame;  


//2nd create methods and constructor   
    public class CheckboxExmpl extends JFrame
    { 
         CheckboxExmpl(){ 
           JFrame f= new JFrame(“Checkbox Exmpl”); 
            Checkbox checkbox1 = new Checkbox(“Java 7”); 
            checkbox1.setBounds(100,100, 50,50); 
            Checkbox checkbox2 = new Checkbox(“Java 8”, true); 
            checkbox2.setBounds(100,150, 50,50); 
            f.add(checkbox1); 
            f.add(checkbox2); 
            f.setSize(300,300); 
            f.setLayout(null); 
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         }  

//call and run the object
    public static void main(String args[]) 
    { 
        new CheckboxExmpl(); 
    } 
    }  

This will output :

Java PopUpMenu Ft. MouseListener

First I want you to do this one thing, right click on any part of this page (besides a link), okay… have you done it? if you’ve done it you can see that there will be a PopUp in the page, the PopUp usually contains : copy, cut, paste, selectAll, savePages etc. Now we’ll try to do it ourself using Java, so buckle up and prepare your IDE’s.

A PopUpMenu can be dynamically popped up anywhere at any specific position within a component. A PopUpMenu also inherits the class of Menu.

PopUpMenu Declaration :

public class PopupMenu extends Menu implements MenuContainer

after that, it’s Exmpl time!
 okay I’ve notice that if I write the code into separate pieces and re-write it again, it’ll be too long.. so now I’ll just write the code once and separate them with comments, let’s go :


// 1st Import

 package Menu;
    import java.awt.*; 
    import java.awt.event.*;
    import javax.swing.JFrame; 

  
// Create the main class, constructor, methods etc.
    class PopupMenuExmpl extends JFrame
    { 
         PopupMenuExmpl(){ 
             JFrame f= new JFrame(“PopupMenu Example”); 
             final PopupMenu popupmenu = new PopupMenu(“Edit”);   //creates the popup
             MenuItem cut = new MenuItem(“Cut”);  //creates the menuItem (cut)
             cut.setActionCommand(“Cut”); 
             MenuItem copy = new MenuItem(“Copy”);  //creates the menuItem (copy)
             copy.setActionCommand(“Copy”); 
             MenuItem paste = new MenuItem(“Paste”);  //creates the menuItem (paste)
             paste.setActionCommand(“Paste”);     
             popupmenu.add(cut);  // add (cut) to Menu
             popupmenu.add(copy);
// add (copy) to Menu 
             popupmenu.add(paste); // add (paste) to Menu     

       
             f.addMouseListener(new MouseAdapter() {  //adds the MouseListener
                public void mouseClicked(MouseEvent e) {             
                    popupmenu.show(f , e.getX(), e.getY()); 
                }                
             }); 
             f.add(popupmenu);  
             f.setSize(300,300); 
             f.setLayout(null);  // these are all just basic JFrame thing you probably already know
             f.setVisible(true); 
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         }  

// Create the main static method and run the Object
    public static void main(String args[]) 
    { 
            new PopupMenuExmpl();  //call and runs the method and object.
    } 
   }   

This will output :

Java JProgressBar

Okay today we’ll create something called a JProgressBar, you probably could already know what a know what a progressBar is, well if you don’t know it’s like when you’re watching youtube and video player has a red that keeps going based on the time of the video, or when you’re playing video games and it is loading to the next part, it all has a good example of progressBar but today we’ll create something simple, which look like this :


Okay we’ll setoff by importing every package that we needs, here is the package that you should import :

    import javax.swing.*; 

yup, that’s it! because there is an asterisk (*) sign at the end of javax.swing. syntax, that means we’re importing everything from inside the swing package.
After that part is done, now we’ll create the main public method, the constructor and every method that we’re going to need in this program :

 public class progressBar extends JFrame{
  progressBar(){
  }
  public void iterate(){
  }
   public static void main(String[] args){
  }
}

Now the framework of the program is done, we’ll fill it step by step now, first we’ll create everything that’s basic, and we’ll also fill the constructor first :

public class progressBar extends JFrame{
    JProgressBar jb;  //create a new JProgressBar that is instantiated as jb
    int i=0,num=0; //create 2 variable that we’re going to need later

 progressBar(){
  jb=new JProgressBar(0,2000);  
  //create a new JProgressBar with the time length of the progress it is based on
    jb.setBounds(100,150,200,30);  //set the size and boundaries of the JProgressBar
         
    jb.setValue(0);  //set the value first to 0
    jb.setStringPainted(true);  //makes the string able to be painted

         
    add(jb);  //add jb to the JFrame
    setSize(400,400);  //set the size of the JFrame
    setLayout(null);  //set the Layout to be null

 }
}

That part is done now, we’ll fill the iterate() method and public static void main method, this 2 methods should be inside the progressBar class :

public void iterate(){ 
    while(i<=2000){  //creates a while loop, when value of i <= 2000
      jb.setValue(i);  

     //now it will change the value of the jb.setValue that we set earlier based on the progress
      i=i+20;  //keeps changing i to be incremented by 20 while value of i <= 2000
      try{Thread.sleep(150);}catch(Exception e){}  

      //try to Thread.sleep for 150 ms and if it doesn’t work catch it as an exception
    } 
    } 
    public static void main(String[] args) { 
        progressBar pb=new progressBar();  //call the object
        pb.setVisible(true);  //makes progressBar to be visible
        pb.iterate();  //run the iterate() method
    } 

 
And together it should look like this :

 import javax.swing.*; 
    public class progressBar extends JFrame{ 

        private static final long serialVersionUID = 1L;
    JProgressBar jb; 
    int i=0,num=0; 
     
    progressBar(){ 
    jb=new JProgressBar(0,200); 
    jb.setBounds(100,150,200,30); 
         
    jb.setValue(0); 
    jb.setStringPainted(true); 
         
    add(jb); 
    setSize(400,400); 
    setLayout(null); 
    } 
     
    public void iterate(){ 
    while(i<=200){ 
      jb.setValue(i); 
      i=i+2; 
      try{Thread.sleep(150);}catch(Exception e){} 
    } 
    } 
    public static void main(String[] args) { 
        progressBar pb=new progressBar(); 
        pb.setVisible(true); 
        pb.iterate(); 
    } 
    }