N Queen Visualizer Sample Java Program

Explanation:

TODO.

This is just a sample program for anyone trying to implement their own version of N Queen Visualizer. This may be modified to create animation for other problems such as knight’s tour.

This version doesn’t have much. Blue cells represent empty / non traversed cells. White cells represent traversed but backtracked from that cell to another cell meaning its not part of Solution. Finally orange cells represent solutions.

The theory and code is explained here in geeksforgeeks.

Get the newest code from my github [TODO] code repository. I will update it eventually.

App Screenshots:

java n queen solver animation screenshot
java n queen solver animation screenshot

N Queen Code:

/**
 * Author:      Asif Ahmed
 * Site:        https://quickgrid.wordpress.com
 * Description: N Queen visualizer Sample.
 */

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

/**
 * Created by computer science on 12/6/2015.
 */
public class App {

    final static int M = 8;
    static JLabel [][] jLabel = new JLabel[M][M];


    static int board[][] = new int[M][M];


    static void printSolution(){

        for(int i = 0; i < M; ++i){
            for(int j = 0; j < M; ++j){
                System.out.printf("%d ", board[i][j]);
            }
            System.out.printf("\n");
        }

    }


    static boolean isSafe( int row, int col ) {

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < col; ++i)
            if (board[row][i] == 1)
                return false;


        for (int i = row, j = col; i >= 0 && j >= 0; --i, --j) {

            if (board[i][j] == 1)
                return false;

        }

        for (int i = row, j = col; i < M && j >= 0; ++i, --j){

            if (board[i][j] == 1)
                return false;
         }

        return true;
    }



    static boolean findSolution( int col ){

        if(col >= M)
            return true;


        for( int i = 0; i < M; ++i ){

            //Increase the sleep value to slow down the animation
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if( isSafe( i, col) == true ){

                board[i][col] = 1;
                jLabel[i][col].setBackground(Color.ORANGE);


                if( findSolution( col + 1) == true )
                    return true;


                board[i][col] = 0;
                jLabel[i][col].setBackground(Color.WHITE);

            }

        }


        return false;

    }

    static void solveNQueen(){



        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        // reset board
        for(int i = 0; i < M; ++i) {
            for (int j = 0; j < M; ++j) {

                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                board[i][j] = 0;
                jLabel[i][j].setBackground(Color.BLUE);
            }
        }



        //If solution exist print otherwise show error message
        if( findSolution( 0 ) == false )
            System.out.println("No Solution.\n");
        else
            printSolution();

    }




    App() {


        JFrame jFrame = new JFrame("NQueen Visualizer.");

        jFrame.setLayout(new GridLayout(M, M));
        jFrame.setSize(400, 400);

        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);


        for(int i = 0; i < M; ++i) {
            for (int j = 0; j < M; ++j) {
                jLabel[i][j] = new JLabel( "(" + i + "," + j + ")" );
                jLabel[i][j].setHorizontalAlignment(SwingConstants.CENTER);

                jLabel[i][j].setSize(50, 50);

                jLabel[i][j].setOpaque(true);

                //Random rand = new Random();
                //jLabel[i].setBackground(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));

                jFrame.add(jLabel[i][j]);
            }
        }


        jFrame.setVisible(true);

    }






    public static  void main( String args[] ){

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new App();
            }
        });

        solveNQueen();

    }

}
Advertisements

Java Collections Generics List and ArrayList Methods Usage tutorial

Java Collections Generics List and ArrayList Method Usage tutorial:

The code below contains usage of various collection framework methods with overloaded mehtods such as add, addAll, set, get, contains, remove, sort, isEmpty. Also usage of iterator, list iterator, comparator, enhanced for loop, foeEach, lambda expression, list to array conversion, adding Integer list items to string list, custom data structure list of lists etc.

Get the Latest code from my Github repository here:

https://github.com/quickgrid/JavaProgramming/blob/master/src/javacode/collectionsexample/ListTest.java

If you have trouble reading the code head over to the github link. Github source is a lot easier on the eyes than reading here.

Please delete or modify the package statement if your folder structure is different.

list tutorial output 1
list tutorial output 1
list tutorial output 2
list tutorial output 2
list tutorial output 3
list tutorial output 3

 

Code:

package javacode.collectionsexample;

import java.util.*;

/**
 * Created by asif on 9/2/2015.
 */
public class ListTest {
    public static void main(String [] args){


        /*******************************************************************************************/
        // Creating a generic String list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 1:");
        System.out.println("===========");


        // It is optional to write string inside angle brackets " new ArrayList<String>() "
        List<String> list1 = new ArrayList<>();

        // Add items to the list
        // since the list was string type trying to put other variables types will result in error
        for(int i = 0; i < 5; ++i)
            list1.add(i + "");

        // See how many elements are in the list
        System.out.println("Items in the list 1: " + list1.size());


        System.out.println();
        /*******************************************************************************************/
        // Adding items in for loop
        /*******************************************************************************************/
        System.out.println("TUTORIAL 2:");
        System.out.println("===========");

        List<String> list2 = new ArrayList<>();

        for(int i = 4; i >= 0; --i)
            list2.add(i + "");

        System.out.println("Items in the list 2: " + list2.size());


        System.out.println();
        /*******************************************************************************************/
        // Checking if all items in a collection exist in another collection
        /*******************************************************************************************/
        System.out.println("TUTORIAL 3:");
        System.out.println("===========");


        int index = 0;

        // Both list contains same items but they are in different order
        // So here it checks if all items from one collection is available in another collection
        if(list1.containsAll(list2)){

            // just like array we can access or get elements by its index
            System.out.println("Elements in the given " + index + " index: (list1["+ index + "], list2[" + index + "]) = (" + list1.get(index) + ", " + list2.get(index) + ")");

        }


        System.out.println();
        /*******************************************************************************************/
        // Checking if a list contains a certain item
        /*******************************************************************************************/
        System.out.println("TUTORIAL 4:");
        System.out.println("===========");


        // Check if a certain element belongs to a collection
        String my_element = "3";

        if(list2.contains( my_element )){

            // Now that we know that the collections contains the given element lets get the index
            System.out.println("List contains given element at index: " + list2.indexOf(my_element));

        }


        System.out.println();
        /*******************************************************************************************/
        // Using iterator to traverse a list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 5:");
        System.out.println("===========");


        // append all the items in list2 to list1
        list1.addAll(list2);

        // Create an iterator to iterate over all the items in list
        Iterator iterator = list1.iterator();

        // using hasNext to check if the next element exist
        while (iterator.hasNext()){
            System.out.print(iterator.next() + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Adding items to a generic Integer list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 6:");
        System.out.println("===========");


        // create a new list of integers
        List<Integer> list3 = new ArrayList<>();

        for (int i = 0; i < 5 ; ++i) {
            list3.add( i * 2 );
        }

        System.out.print("Current list 3 items: ");

        // Enhanced for loop to print current items in list2
        for(Integer i : list3){
            System.out.print(i + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Converting a list to an array
        /*******************************************************************************************/
        System.out.println("TUTORIAL 7:");
        System.out.println("===========");


        // Convert list of integer into an integer array
        Integer[] array = new Integer[list3.size()];
        list3.toArray(array);

        System.out.print("After conversion of list 3 to array: ");

        for (int i = 0; i < array.length; ++i) {
            System.out.print(array[i] + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Printing list items using forEach lambda expression
        /*******************************************************************************************/
        System.out.println("TUTORIAL 8:");
        System.out.println("===========");


        list3.forEach(
                // Lambda expression
                // In the loop add each elements in list3 to list2
                // since list3 is of Integer type and list2 is of String Type and i am adding to list2
                // So each item of list2 should be cast to String
                items -> list2.add(Integer.toString(items))
        );

        System.out.print("After adding list3 to list2: ");

        // Using Stream to print all items in the list
        list2.forEach(
                // java will try to determine the type
                i -> System.out.print(i + ", ")
        );
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Adding an item to the list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 9:");
        System.out.println("===========");


        // Add items in the list 2 adds to last position of the list
        list2.add("Asif");

        System.out.print("After calling add function: ");
        list2.forEach(i -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Add object at a specific index
        /*******************************************************************************************/
        System.out.println("TUTORIAL 10:");
        System.out.println("===========");


        // An overload add method takes an index to place in as first argument
        // The second argument is the element to add
        list2.add(1, "Quickgrid");

        System.out.print("After calling overloaded add function: ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Remove object at a specific index
        /*******************************************************************************************/
        System.out.println("TUTORIAL 11:");
        System.out.println("===========");


        // It will remove the item on the 0th position of the list
        list2.remove(0);

        System.out.print("After calling remove with index: ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Sort a list using default comparators
        /*******************************************************************************************/
        System.out.println("TUTORIAL 12:");
        System.out.println("===========");


        // It will Sort the list with default comparator
        list2.sort(Comparator.<String>naturalOrder());

        System.out.print("After Sorting list 2 with comparator : ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Replacing object at a given location
        /*******************************************************************************************/
        System.out.println("TUTORIAL 13:");
        System.out.println("===========");


        // It will replace an element in the given index
        list2.set(1, "Almost there");

        System.out.print("After replacing given index with an item: ");
        list2.forEach((String i) -> System.out.print(i + ", "));
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Getting a specific sub list from a list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 14:");
        System.out.println("===========");


        System.out.print("Print the sublist from a given index to another index: ");

        // Print the sublist from a given index to another index
        System.out.println(list2.subList(2, 8));


        System.out.println();
        /*******************************************************************************************/
        // Iterating list backwards using bidirectional ListIterator
        /*******************************************************************************************/
        System.out.println("TUTORIAL 15:");
        System.out.println("===========");


        // Print list 3 in reverse order using bidirectional ListIterator
        // Takes an optional parameter from which index to start from
        ListIterator<Integer> iit = list3.listIterator(list3.size());

        System.out.print("Traversing list 3 in reverse order using ListIterator: ");

        while (iit.hasPrevious()){
           System.out.print(iit.previous() + ", ");
        }
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // Clearing or emptying a list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 16:");
        System.out.println("===========");


        // Delete all items in the list
        list3.clear();

        // Check if the list is empty
        if(list3.isEmpty()){
            System.out.println("End of tutorial.....");
        }


        System.out.println();
        /*******************************************************************************************/
        // Creating a custom data structure using list
        /*******************************************************************************************/
        System.out.println("TUTORIAL 17:");
        System.out.println("===========");


        // Creating custom data structure list of lists
        List< List<String> > listOfList = new ArrayList<>();
        listOfList.add(list1);
        listOfList.add(list2);

        // It will get the second list from the list of list
        // Then get the last element of that list
        System.out.println(
                listOfList.get(1).get(list2.size() - 1)
        );


        System.out.println();
        /*******************************************************************************************/
        // List order after adding elements
        /*******************************************************************************************/
        System.out.println("TUTORIAL 18:");
        System.out.println("===========");


        // List doesn't replace the element in an index if any element exist
        // It shifts the elements back and insert the current element

        System.out.println("Elements before inserting: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();

        System.out.println("Size before inserting: " + list2.size());

        // Inserting at a index
        list2.add(9, "Asif");

        System.out.println("Size after inserting: " + list2.size());

        System.out.println("Elements After inserting: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // List order after removing elements
        /*******************************************************************************************/
        System.out.println("TUTORIAL 19:");
        System.out.println("===========");


        // On removal of an item from the list, items right to the removing item will shift back left
        // Also if the are multiple object with same value, remove will only remove one of them
        // Removing by index return the value at that index
        // Removing by value return true if the value is found otherwise false

        System.out.println("Elements before removing: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();

        System.out.println("Size before removing: " + list2.size());

        // removing by object
        boolean found = list2.remove("Asif");
        System.out.println("Element to remove found? : " + found);

        // removing by index
        String itemRemovedByIndex = list2.remove(1);
        System.out.println("Item removed by index: " + itemRemovedByIndex);


        System.out.println("Size after removing: " + list2.size());

        System.out.println("Elements After removing: ");

        list2.forEach(
                item -> System.out.print(item + ", ")
        );
        System.out.println();


        System.out.println();
        /*******************************************************************************************/
        // List order after removing elements
        /*******************************************************************************************/
        System.out.println("TUTORIAL 20:");
        System.out.println("===========");

        // Nothing yet
    }
}

Java GUI Text and HTML File Loading from File System using JFileChooser

How the app works:

You can load a text or html file from file system running the code or using this simple jar application. Only load button under file menu is implemented to keep it simple. You can also use file compression software’s such as 7-zip to see and extract the contents of the jar file.

Download the project and jar file from this github repository. [ TODO ]

file loader application
file loader application
jfilechooser
jfilechooser
loaded text
loaded text

Directory Structure:

please note the package statement. This is only valid if the code is inside a folder name “gui” and the “gui” folder is inside “javacode” folder. Use Dr. Java for easily running this code ( create a class with this class name and delete the package statement  ) otherwise use intellij idea.

directory structure
directory structure

Code File Loader Application:

// if you do not use a directory structure like mine 
// then delete the line below or modify it to your need
package javacode.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URI;

/**
 * Created by asif on 8/16/2015.
 *
 * Simple File Loader Application using JFileChooser
 * Events are handled for only load button for simplicity
 * You can add more based on necessity
 */
public class FileLoaderApplication {

    JFrame jFrame;
    MenuBar menuBar;
    Menu file, edit, help;
    MenuItem loadItem, newItem, closeItem, exitItem, cutItem, copyItem, pasteItem, divideItem;
    TextArea textArea;
    JFileChooser jFileChooser;

    public FileLoaderApplication() {
        jFrame = new JFrame("Menu window");

        textArea = new TextArea();
        menuBar = new MenuBar();
        jFileChooser = new JFileChooser();

        file = new Menu("File");
        edit = new Menu("Edit");
        help = new Menu("Help");

        loadItem = new MenuItem("Load");
        newItem = new MenuItem("New");
        closeItem = new MenuItem("Close");
        exitItem = new MenuItem("Exit");
        cutItem = new MenuItem("Cut");
        copyItem = new MenuItem("Copy");
        pasteItem = new MenuItem("Paste");
        divideItem = new MenuItem("-------");
    }

    public static void main(String [] args){
        FileLoaderApplication t = new FileLoaderApplication();
        t.showFrame();
    }

    public void showFrame(){
        file.add(loadItem);
        loadItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // load a file from file system
                    jFileChooser.showOpenDialog(jFrame);
                    FileReader fr = new FileReader(jFileChooser.getSelectedFile());

//                    FileReader fr = new FileReader("javacode/gui/in.txt");

                    // read bytes from the file
                    // use BufferedReader for faster reading
                    int s = fr.read();
                    String a = "";
                    while (s != -1) {
                        a += (char) s;
                        s = fr.read();
                    }

                    //a = a.replaceAll("\\s+", " ");

                    textArea.setText(a);

                } catch (Exception e1) {
                    textArea.setText("Error Loading File");
                    e1.printStackTrace();
                }
            }
        });

        file.add(newItem);
        file.add(closeItem);
        file.add(divideItem);
        file.add(exitItem);

        edit.add(cutItem);
        edit.add(copyItem);
        edit.add(pasteItem);

        menuBar.add(file);
        menuBar.add(edit);
        menuBar.add(help);

        textArea.setPreferredSize(new Dimension(380, 300));
        textArea.repaint();
        jFrame.add(textArea);

        jFrame.setLayout(new FlowLayout());
        jFrame.setSize(new Dimension(400, 400));

        jFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        jFrame.setVisible(true);

        jFrame.setMenuBar(menuBar);
    }

}

 

Creating the jar File:

Read below only if your directory structure looks like mine or you have other unnecessary files in your project.

Since I am not working in the default directory and there are other classes in my project. So some things are needed to be changed. First see my tutorial on creating a jar artifact in intellij idea.
Now following that tutorial you will be able to create a working jar. But it will also have other useless files which in turns increase the jar size.  One way to fix that problem is shown below.

Go to File->Project Structure->Modules->Sources
Now right-click and select exclude for any module you don’t want the jar to get compiled with.
fix project structure
fix project structure

A Brief Presentation on Java Collections Framework

Most information here is taken from oracle documentation of Java Standard Edition 8 version of the website. If you want to learn more follow the links on the references page.

Download the java collections framework presentation pdf or read below.

Visualizing a bit differently:

different visualization of core collections interfaces
different visualization of core collections interfaces

 

Slides:

definitions framework, algorithm and collection
definitions framework, algorithm and collection
java collection framework introduction
java collection framework introduction
collections interfaces
collections interfaces
Collections Interface hierarchy
Collections Interface hierarchy
compactor and iterator
compactor and iterator
an example code of collections usage
an example code of collections usage
concurrent programming
concurrent programming
Collections Data structures implementation chart
Collections Data structures implementation chart
Collections Algortihms
Collections Algortihms
references
references

 

Java Swing GUI Internationalization and String Separation using ResourceBundle and Locale

Java Swing GUI  Internationalization and String Separation using ResourceBundle and Locale:

Before proceeding take note of the directory structure of the highlighted part otherwise it won’t work. Or, just fork this repository from Github from this link,

https://github.com/quickgrid/QuickEditor

Output:

java swing internationalization output
java swing internationalization output

Directory Structure:

internationalization directory structure
internationalization directory structure

 


Codes:

Here I have separated all strings to a directory res/locale using ResourceBundle class. But I have only shown Internationalization for the application name using the Locale class to specify which locale it is going to use. Here one of the locale is French another is English. More can be added.

For the menubar Menus I have used ResourceBundle class to separate them for easier modification later. They too can be internationalized using Locale. If the Locale class based codes are deleted here then it will switch to the default properties filename. Note if you cut the ‘locale’ parameter in line 53 then the window name will be “Quick Ide” since it will switch to the default one.

Lastly I have separated the menu creation logic to another class called AddMenu. Note I have only added two Menu but more can be added.

Learn more on Internationalization.

Some important things are highlighted below.

QuickEditor.java
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Created by asif on 8/18/2015.
 */
public class QuickEditor {
    /**
     * variables declaration
     */
    JFrame jFrame;
    JMenuBar jMenuBar;


    /**
     * ResourceBundle variables for internationalization and easier modification
     */
    ResourceBundle appNameResourceBundle;

    /**
     * AddMenu class add new JMenu and JMenuItem to the JMenuBar
     */
    AddMenu addMenu;


    public QuickEditor(){
        prepareResourceBundle();

        jFrame = new JFrame(appNameResourceBundle.getString("ApplicationName"));

        jMenuBar = new JMenuBar();

        addMenu = new AddMenu(jMenuBar);

    }

    private void prepareResourceBundle() {

        /**
         * Delete this portion in case you are just separating string from the code
         * also delete the 'locale' argument in the next portion
         */
        String country = new String("fr");
        String language = new String("Fr");
        Locale locale = new Locale(country, language);

        /**
         * The dot specifies a directory before the file name
         */
        appNameResourceBundle = ResourceBundle.getBundle("res.locale.ApplicationName", locale);
    }

    public void prepareGUI(){
        jFrame.setSize(400, 400);
        jFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
            }
        });

        /**
         * addComponents is a method in AddMenu Class which adds JMenu to JMenuBar
         */
        addMenu.addComponents();

        jFrame.setJMenuBar(jMenuBar);
        jFrame.setVisible(true);
    }

    public static void main(String [] args){
        QuickEditor quickEditor = new QuickEditor();
        quickEditor.prepareGUI();
    }
}

 


AddMenu.java
import javax.swing.*;
import java.util.ResourceBundle;

/**
 * Created by asif on 8/18/2015.
 */
public class AddMenu {
    JMenuBar jMenuBar;
    JMenu fileMenu, viewMenu, helpMenu;
    ResourceBundle menuResourceBundle;

    public AddMenu(JMenuBar jMenuBar) {
        this.jMenuBar = jMenuBar;
        menuResourceBundle = ResourceBundle.getBundle("res.locale.Menus");
        createComponentObjects();
    }

    public void createComponentObjects(){
        fileMenu = new JMenu(menuResourceBundle.getString("FileMenu"));
        viewMenu = new JMenu(menuResourceBundle.getString("ViewMenu"));
    }

    public void addComponents(){
        jMenuBar.add(fileMenu);
        jMenuBar.add(viewMenu);
    }
}

 


Menus.properties
# This is comment
# Created by asif on 8/18/2015.
# I have created some Menu names by default

FileMenu = File
EditMenu = Edit
ViewMenu = View
CodeMenu = Code
ToolsMenu = Tools
WindowMenu = Window
HelpMenu = Help

 


ApplicationName.properties
ApplicationName = Quick IDE

 


ApplicationName_fr_FR.properties
ApplicationName = Rapide IDE

Java Resource Loading using URL class

Java Relative Path Resource Loading using URL class:

This code is continuation of this Java AWT Piano Button Click Sound.

Github Repo:

I have made a github repository for this project. Get it here,

https://github.com/quickgrid/SimpleAwtGUIProject

Until this point i used a string to identify location of my resources ( *.wav audio files ). Now i will use getClass().getResource(“resourceName.extension”) to load resources from my class path.  Here getResources() will return an URL type object so here i store it in URL url variable. Then i pass that variable to AudioSystem.getAudioInputStream(url).

Next Creating jar files ( artifacts ) of this application in Intellij idea IDE.

Only changes from last version is highlighted below. Note that import statements may have changed but i haven’t highlighted them.


 

Code:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;

/**
 * Created by asif on 8/15/2015.
 */
public class SimpleAwtGui implements ActionListener {
    private static final int button_count = 10;

    // Declare a Frame type variable
    Frame frame;
    MenuBar menuBar;
    Menu fileMenu, optionsMenu, helpMenu;
    Panel panelUpperSection, panelLowerSection;
    Label labelButtonPressHeading, labelButtonPressed;

    // Create an array of Button type Objects
    Button[] button = new Button[button_count];

    public SimpleAwtGui() {
        // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");

        // Create MenuBar Object
        menuBar = new MenuBar();

        createPanels();
        createLabels();
        createButtons();
        createMenu();
    }

    private void createMenu() {
        // Create Menu objects to add to the MenuBar
        fileMenu = new Menu("File");
        optionsMenu = new Menu("Options");
        helpMenu = new Menu("Help");
    }

    private void createPanels() {
        // Create a panel object for organizing content
        panelUpperSection = new Panel();
        panelLowerSection = new Panel();
    }

    private void createLabels() {
        // create Label
        labelButtonPressHeading = new Label();
        labelButtonPressed = new Label();
    }

    private void createButtons() {
        // Use for loop to instantiate every button object
        for (int i = 0; i < button_count; ++i) {
            button[i] = new Button("" + i);
            button[i].setActionCommand("" + i);

            // if i is odd then change the button color
            if (i % 2 == 1) {
                button[i].setBackground(Color.BLACK);
                button[i].setForeground(Color.WHITE);
            }
        }
    }


    // Not necessary but good practice all codes inside this can be written inside main
    public void showFrame() {
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new GridLayout(2, 1));

        addPanels();

        addLabels();

        // Add all of the buttons to the layout
        for (int i = 0; i < button_count; ++i) {
            panelLowerSection.add(button[i]);
            button[i].addActionListener(this);
        }

        // handles various window events
        handleWindowEvents();

        // Add Menu to MenuBar
        addMenuBarMenus();

        // Add MenuItem to Menu
        addMenuItems();

        // Add MenuBar to the Frame
        frame.setMenuBar(menuBar);

        // set the frame visible otherwise nothing will be shown
        frame.setVisible(true);
    }

    private void addPanels() {
        // Add panel to the frame
        frame.add(panelUpperSection);
        frame.add(panelLowerSection);

        // Set Layout for the panels
        panelUpperSection.setLayout(new BorderLayout());
        panelLowerSection.setLayout(new GridLayout());

        // Add Label to Panel
        panelUpperSection.add(labelButtonPressHeading, BorderLayout.NORTH);
        panelUpperSection.add(labelButtonPressed, BorderLayout.CENTER);
    }

    private void addLabels() {
        labelButtonPressHeading.setBackground(Color.BLACK);
        labelButtonPressHeading.setText("Buttons clicked will be shown Below:");
        labelButtonPressHeading.setForeground(Color.WHITE);

        labelButtonPressed.setBackground(Color.DARK_GRAY);
        labelButtonPressed.setForeground(Color.WHITE);
    }

    private void handleWindowEvents() {
        // Register window listener event to the frame without implementing WindowListener
        frame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );
    }

    private void addMenuBarMenus() {
        // Add Menu to the MenuBar
        menuBar.add(fileMenu);
        menuBar.add(optionsMenu);
        menuBar.add(helpMenu);
    }

    private void addMenuItems() {
        // Add items to File Menu
        fileMenu.add(new MenuItem("New"));
        fileMenu.add(new MenuItem("Open"));
        fileMenu.add(new MenuItem("Exit"));

        // Add items to File Menu
        optionsMenu.add(new MenuItem("Options"));

        // Add items to File Menu
        helpMenu.add(new MenuItem("Help"));
        helpMenu.add(new MenuItem("About"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int i = Integer.parseInt(e.getActionCommand());

        if (i % 2 == 1) {
            labelButtonPressed.setText("Odd buttons Pressed");
            URL url = getClass().getResource("a.wav");
            playSound(url);
        } else {
            labelButtonPressed.setText("Even buttons Pressed");
            URL url = getClass().getResource("b.wav");
            playSound(url);
        }
    }

    public void playSound(URL url) {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
            Clip clip = AudioSystem.getClip();
            clip.stop();
            clip.open(audioInputStream);
            clip.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        // Create an instance of SimpleAwtGui
        SimpleAwtGui gapp = new SimpleAwtGui();

        // call the showFrame() function to display the window
        gapp.showFrame();


    }

}

Java AWT Piano Button Click Sound

Java AWT Piano Button Click Sound :

This code is continuation of this JAVA AWT CHANGE LABEL TEXT BASED ON BUTTON EVENTS.

Copy the codes below and save them in a file called “SimpleAwtGui.java”. Be aware of  the case of the file name as the class name should match file name.

Here I’ve used a relative path (relative against project file path) for my sound file. But it will create problem once the class is packaged. I will fix that in the next post. Here my sound file is located inside src folder where SimpleAwtGui.java is also located.

Java can not play mp3 without external plugins or javafx. It can play wav files but they need to be 8 or 16 bit. There are many free sound websites download wav files from there and paste it in the same folder as your java file. If that doesn’t work then use an absolute path for example, “C:\\sound.wav”. Another way is directly pasting inside intellij idea src folder.

Also all of the buttons play the same sound since I’ve added same music file for all the buttons. They can be modified to play different sound with different button clicks.

Only changes from last version is highlighted below.


Sample:

button events click sound
button events click sound

 

Code:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

/**
 * Created by asif on 8/15/2015.
 */
public class SimpleAwtGui implements ActionListener {
    private static final int button_count = 10;

    // Declare a Frame type variable
    Frame frame;
    MenuBar menuBar;
    Menu fileMenu, optionsMenu, helpMenu;
    Panel panelUpperSection, panelLowerSection;
    Label labelButtonPressHeading, labelButtonPressed;

    // Create an array of Button type Objects
    Button[] button = new Button[button_count];

    public SimpleAwtGui() {
        // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");

        // Create MenuBar Object
        menuBar = new MenuBar();

        createPanels();
        createLabels();
        createButtons();
        createMenu();
    }

    private void createMenu() {
        // Create Menu objects to add to the MenuBar
        fileMenu = new Menu("File");
        optionsMenu = new Menu("Options");
        helpMenu = new Menu("Help");
    }

    private void createPanels() {
        // Create a panel object for organizing content
        panelUpperSection = new Panel();
        panelLowerSection = new Panel();
    }

    private void createLabels() {
        // create Label
        labelButtonPressHeading = new Label();
        labelButtonPressed = new Label();
    }

    private void createButtons() {
        // Use for loop to instantiate every button object
        for (int i = 0; i < button_count; ++i) {
            button[i] = new Button("" + i);
            button[i].setActionCommand("" + i);

            // if i is odd then change the button color
            if (i % 2 == 1) {
                button[i].setBackground(Color.BLACK);
                button[i].setForeground(Color.WHITE);
            }
        }
    }


    // Not necessary but good practice all codes inside this can be written inside main
    public void showFrame() {
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new GridLayout(2, 1));

        addPanels();

        addLabels();

        // Add all of the buttons to the layout
        for (int i = 0; i < button_count; ++i) {
            panelLowerSection.add(button[i]);
            button[i].addActionListener(this);
        }

        // handles various window events
        handleWindowEvents();

        // Add Menu to MenuBar
        addMenuBarMenus();

        // Add MenuItem to Menu
        addMenuItems();

        // Add MenuBar to the Frame
        frame.setMenuBar(menuBar);

        // set the frame visible otherwise nothing will be shown
        frame.setVisible(true);
    }

    private void addPanels() {
        // Add panel to the frame
        frame.add(panelUpperSection);
        frame.add(panelLowerSection);

        // Set Layout for the panels
        panelUpperSection.setLayout(new BorderLayout());
        panelLowerSection.setLayout(new GridLayout());

        // Add Label to Panel
        panelUpperSection.add(labelButtonPressHeading, BorderLayout.NORTH);
        panelUpperSection.add(labelButtonPressed, BorderLayout.CENTER);
    }

    private void addLabels() {
        labelButtonPressHeading.setBackground(Color.BLACK);
        labelButtonPressHeading.setText("Buttons clicked will be shown Below:");
        labelButtonPressHeading.setForeground(Color.WHITE);

        labelButtonPressed.setBackground(Color.DARK_GRAY);
        labelButtonPressed.setForeground(Color.WHITE);
    }

    private void handleWindowEvents() {
        // Register window listener event to the frame without implementing WindowListener
        frame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );
    }

    private void addMenuBarMenus() {
        // Add Menu to the MenuBar
        menuBar.add(fileMenu);
        menuBar.add(optionsMenu);
        menuBar.add(helpMenu);
    }

    private void addMenuItems() {
        // Add items to File Menu
        fileMenu.add(new MenuItem("New"));
        fileMenu.add(new MenuItem("Open"));
        fileMenu.add(new MenuItem("Help"));

        // Add items to File Menu
        optionsMenu.add(new MenuItem("Options"));

        // Add items to File Menu
        helpMenu.add(new MenuItem("Help"));
        helpMenu.add(new MenuItem("About"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int i = Integer.parseInt(e.getActionCommand());

        if (i % 2 == 1) {
            labelButtonPressed.setText("Odd buttons Pressed");
            String fileName = "src\\sound.wav";
            playSound(fileName);
        } else {
            labelButtonPressed.setText("Even buttons Pressed");
            String fileName = "src\\sound.wav";
            playSound(fileName);
        }
    }

    public void playSound(String fileName) {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(fileName));
            Clip clip = AudioSystem.getClip();
            clip.stop();
            clip.open(audioInputStream);
            clip.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        // Create an instance of SimpleAwtGui
        SimpleAwtGui gapp = new SimpleAwtGui();

        // call the showFrame() function to display the window
        gapp.showFrame();

    }

}

Java AWT Change Label Text based on Button Events

Java AWT Change Label Text based on Button Events :

This code is continuation of this Java Frame Change Button Colors Based on Even Odd Logic.

Quite a bit has changed since last version. I have put some codes into functions to make them organize. I will not separate the code into multiple files though to keep it simple. Copy the codes below and save them in a file called SimpleAwtGui.java

Be aware of  the case of the file name as the class name should match file name. Change in this code from last version is ActionListener interface is implemented to handle button events. It has only one method ActionPerformed which is used to deal different actions. Here i change label based on which button was clicked.

Here I’ve used setActionCommand to identify which key was pressed based on my assigned command.


Sample:

button events change label 1
button events change label 1
button events change label 2
button events change label 2

 

Code:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

/**
 * Created by asif on 8/15/2015.
 */
public class SimpleAwtGui implements ActionListener {
    private static final int button_count = 10;

    // Declare a Frame type variable
    Frame frame;
    MenuBar menuBar;
    Menu fileMenu, optionsMenu, helpMenu;
    Panel panelUpperSection, panelLowerSection;
    Label labelButtonPressHeading, labelButtonPressed;

    // Create an array of Button type Objects
    Button[] button = new Button[button_count];

    public SimpleAwtGui() {
        // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");

        // Create MenuBar Object
        menuBar = new MenuBar();

        createPanels();
        createLabels();
        createButtons();
        createMenu();
    }

    private void createMenu() {
        // Create Menu objects to add to the MenuBar
        fileMenu = new Menu("File");
        optionsMenu = new Menu("Options");
        helpMenu = new Menu("Help");
    }

    private void createPanels() {
        // Create a panel object for organizing content
        panelUpperSection = new Panel();
        panelLowerSection = new Panel();
    }

    private void createLabels() {
        // create Label
        labelButtonPressHeading = new Label();
        labelButtonPressed = new Label();
    }

    private void createButtons() {
        // Use for loop to instantiate every button object
        for (int i = 0; i < button_count; ++i) {
            button[i] = new Button("" + i);
            button[i].setActionCommand("" + i);

            // if i is odd then change the button color
            if (i % 2 == 1) {
                button[i].setBackground(Color.BLACK);
                button[i].setForeground(Color.WHITE);
            }
        }
    }


    // Not necessary but good practice all codes inside this can be written inside main
    public void showFrame() {
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new GridLayout(2, 1));

        addPanels();

        addLabels();

        // Add all of the buttons to the layout
        for (int i = 0; i < button_count; ++i) {
            panelLowerSection.add(button[i]);
            button[i].addActionListener(this);
        }

        // handles various window events
        handleWindowEvents();

        // Add Menu to MenuBar
        addMenuBarMenus();

        // Add MenuItem to Menu
        addMenuItems();

        // Add MenuBar to the Frame
        frame.setMenuBar(menuBar);

        // set the frame visible otherwise nothing will be shown
        frame.setVisible(true);
    }

    private void addPanels() {
        // Add panel to the frame
        frame.add(panelUpperSection);
        frame.add(panelLowerSection);

        // Set Layout for the panels
        panelUpperSection.setLayout(new BorderLayout());
        panelLowerSection.setLayout(new GridLayout());

        // Add Label to Panel
        panelUpperSection.add(labelButtonPressHeading, BorderLayout.NORTH);
        panelUpperSection.add(labelButtonPressed, BorderLayout.CENTER);
    }

    private void addLabels() {
        labelButtonPressHeading.setBackground(Color.BLACK);
        labelButtonPressHeading.setText("Buttons clicked will be shown Below:");
        labelButtonPressHeading.setForeground(Color.WHITE);

        labelButtonPressed.setBackground(Color.DARK_GRAY);
        labelButtonPressed.setForeground(Color.WHITE);
    }

    private void handleWindowEvents() {
        // Register window listener event to the frame without implementing WindowListener
        frame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );
    }

    private void addMenuBarMenus() {
        // Add Menu to the MenuBar
        menuBar.add(fileMenu);
        menuBar.add(optionsMenu);
        menuBar.add(helpMenu);
    }

    private void addMenuItems() {
        // Add items to File Menu
        fileMenu.add(new MenuItem("New"));
        fileMenu.add(new MenuItem("Open"));
        fileMenu.add(new MenuItem("Help"));

        // Add items to File Menu
        optionsMenu.add(new MenuItem("Options"));

        // Add items to File Menu
        helpMenu.add(new MenuItem("Help"));
        helpMenu.add(new MenuItem("About"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int i = Integer.parseInt(e.getActionCommand());

        if (i % 2 == 1) {
            labelButtonPressed.setText("Odd buttons Pressed");
        } else {
            labelButtonPressed.setText("Even buttons Pressed");
        }
    }

    public static void main(String[] args) {

        // Create an instance of SimpleAwtGui
        SimpleAwtGui gapp = new SimpleAwtGui();

        // call the showFrame() function to display the window
        gapp.showFrame();

    }

}

Adding JavaFx Scene Builder to Intellij idea Ide and Creating Sample Project

Adding JavaFx to Intellij idea Ide:
  1. Download the latest JavaFx Scene builder from Gluonhq and install it.
  2. The application can work standalone without Intellij idea but to use it inside Intellij idea the installation path must be added.
  3. Go to File -> Settings -> Languages & Frameworks -> JavaFx and add the installation path to it.
  4. javafx path example
    javafx path example

     

  5.  Also make sure JavaFx plugin is installed and enabled.
  6. select javafx in new projects menu
    select javafx in new projects menu and click next

     

  7. In the next window name your project
    In the next window name your project and click finish

     

  8. Now in the projects tab go to YourProjectName -> src -> sample there should be two Java Files Main, Controller and sample.fxml
  9. Click on the Scene builder tab in the bottom of the window
    Click on the Scene builder tab in the bottom of the window

     

  10. It should look like this
    It should look like this

     

  11. Now just drag a button from control section and run it
    Now just drag a button from control section and run it

     

     

Java Frame Change Button Colors Based on Even Odd Logic

Java Frame Change Button Colors Based on Even Odd Logic:

This code is continuation of this Java AWT BorderLayout Adding Label to Panel with Color.

Next up handling button press events and adding Sound to button clicks.


Sample:

GridLayout changing button colors
GridLayout changing button colors

 

Code:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Created by asif on 8/13/2015.
 */
public class SimpleAwtGui {

    private static final int button_count = 10;

    // Declare a Frame type variable
    Frame frame;
    MenuBar menuBar;
    Menu fileMenu, optionsMenu, helpMenu;
    Panel panelUpperSection, panelLowerSection;
    Label labelButtonPressHeading, labelButtonPressed;

    // Create an array of Button type Objects
    Button [] button = new Button[button_count];

    public SimpleAwtGui() {
        // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");

        // Create a panel object for organizing content
        panelUpperSection = new Panel();
        panelLowerSection = new Panel();

        // create Label
        labelButtonPressHeading = new Label();
        labelButtonPressed = new Label();

        // Use for loop to instantiate every button object
        for(int i = 0; i < button_count; ++i){
            button[i] = new Button( "" + i );

            // if i is odd then change the button color
            if(i % 2 == 1){
                button[i].setBackground(Color.BLACK);
                button[i].setForeground(Color.WHITE);
            }
        }

        // Create MenuBar Object
        menuBar = new MenuBar();

        // Create Menu objects to add to the MenuBar
        fileMenu = new Menu("File");
        optionsMenu = new Menu("Options");
        helpMenu = new Menu("Help");
    }

    public static void main(String[] args) {

        // Create an instance of SimpleAwtGui
        SimpleAwtGui window = new SimpleAwtGui();

        // call the showFrame() function to display the window
        window.showFrame();

    }

    // Not necessary but good practice all codes inside this can be written inside main
    public void showFrame() {
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new GridLayout(2, 1));

        // Add panel to the frame
        frame.add(panelUpperSection);
        frame.add(panelLowerSection);

        // Set Layout for the panels
        panelUpperSection.setLayout(new BorderLayout());
        panelLowerSection.setLayout(new GridLayout());

        // Add Label to Panel
        panelUpperSection.add(labelButtonPressHeading, BorderLayout.NORTH);
        panelUpperSection.add(labelButtonPressed, BorderLayout.CENTER);

        labelButtonPressHeading.setBackground(Color.BLACK);
        labelButtonPressHeading.setText("Buttons clicked will be shown Below:");
        labelButtonPressHeading.setForeground(Color.WHITE);

        labelButtonPressed.setBackground(Color.darkGray);

        // Add all of the buttons to the layout
        for(int i = 0; i < button_count; ++i) {
            panelLowerSection.add(button[i]);
        }

        // Register window listener event to the frame without implementing WindowListener
        frame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );

        // Add Menu to the MenuBar
        menuBar.add(fileMenu);
        menuBar.add(optionsMenu);
        menuBar.add(helpMenu);

        /**
         * Add MenuItem to Menu
         */

        // Add items to File Menu
        fileMenu.add(new MenuItem("New"));
        fileMenu.add(new MenuItem("Open"));
        fileMenu.add(new MenuItem("Help"));

        // Add items to File Menu
        optionsMenu.add(new MenuItem("Options"));

        // Add items to File Menu
        helpMenu.add(new MenuItem("Help"));
        helpMenu.add(new MenuItem("About"));

        // Add MenuBar to the Frame
        frame.setMenuBar(menuBar);

        // set the frame visible otherwise nothing will be shown
        frame.setVisible(true);
    }
}