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

Creating Java Jar File Artifact in Intellijidea IDE

Creating Java Jar File Artifact in Intellijidea IDE:

Video Tutorial:


This is an independent tutorial. The code is from this tutorial Java Relative Path Resource Loading using URL class. It is not necessary to use this code, any project will work. Here in this tutorial I package the java files and other resources such as sound files to a jar file or an Intellijidea artifact for this project.


 

Text Version of the Tutorial:

In intellijidea an artifact is an output of a project or module. So for our java project our project output is a jar file. So the jar file is the artifact in this project.

 

  1. initial Screen from last tutorial
    initial Screen from last tutorial

     

  2. Go to File -> Project Structure -> Artifacts
  3. artifacts project structure settings
    artifacts project structure settings
  4. Now Select the Plus or Add Sign and click on Jar -> From Modules with Dependencies.
  5. jar artifact settings
    jar artifact settings

     

  6. Now select Main class for your jar file like shown below. The main class is the class with your main method, the entry point for your jar application.
  7. select main class
    select main class
  8. Click ok on eveything else and exit out of project structure dialog.
  9. Now click on the menubar Build->Build Artifacts->Build like shown below.
  10. build jar artifacts
    build jar artifacts
  11. Now see on the left side in the projects area there is a new directory called Out -> Artifacts -> YourProjectName_Jar -> JarFileName.jar
  12. locate jar artifact file
    locate jar artifact file

 

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

    }

}

Vector Calculus Green’s Theorem Math Examples

Vector Calculus Green’s Theorem Math Examples:

These are from the book Calculus Early Transcendentals 10th Edition. Refer to 15.4 exercise maths.

Green’s Theorm:

Let, R be a simple connected plane region where boundary is a simple, closed, piecewise smooth curve oriented counter clockwise. If f(x,y) \text{and} g(x,y) are continuous and have continuous first partial derivatives on some open set containing R, then

\int f(x,y) \ dx + g(x,y) \ dy = \iint\limits_R (\frac{\delta g}{\delta x} - \frac{\delta f}{\delta y}) \ dA

Excercise 3:

Using Green’s Theorem evaluate the integral assuming the curve C is oriented Counter clockwise, \oint_c 4xy \ dx + 2xy \ dy, where C is the Rectangle bounded by x = -2, x = 4, y = 1, y = 2 .

Solution:

greens theorm exercise 3
greens theorm exercise 3
Using Green’s Theorm,
\oint_c 4xy \ dx + 2xy \ dy = \iint\limits_R \frac{\delta }{\delta x} 2xy - \frac{\delta }{\delta y} 4xy \ dA 

              = \iint\limits_R 2y - 4x \ dA 

              = \int_{-2}^4\int_1^2 2y - 4x \ dy \ dx 

              = \int_{-2}^4 [y^2 - 4xy]_1^2 \ dx 

              = \int_{-2}^4 4 - 8x - 1 + 4x \ dx 
 
              = \int_{-2}^4 3 - 4x \ dx 

              = [3x - 2x^2]_{-2}^4 

              = 12 - 32 + 6 + 8 

              = -6 

Excercise 7:

Using Green’s Theorem evaluate the integral assuming the curve C is oriented Counter clockwise, \oint_c (x^2 - 3y) \ dx + 3x \ dy, where C is the circle x^2 + y^2 = 4 .

Solution:

greens theorm exercise 7
greens theorm exercise 7

Since this is a full circle the interval of \int_{\theta} \text{is from} \ 0 \ to \ 2\pi
Also, x^2 + y^2 = 4 = 2^2 . So the interval of \int_{r} \text{is from} \ 0 \ to \ 2

Using Green’s Theorm,
\oint_c (x^2 - 3y) + 3x \ dy = \iint\limits_R \frac{\delta }{\delta x} 3x - \frac{\delta }{\delta y} (x^2 - 3y) \ dA 

               = \iint\limits_R 3 + 3 \ dA 

               = \int_0^{2\pi} \int_0^2 6 r \ dr \ d\theta 
 
               = 6 \int_0^{2\pi} [\frac{r^2}{2}]_0^2 \ dr \ d\theta 

               = 12 \int_0^{2\pi} \ d\theta 

               = 12 [\theta]_0^{2\pi} 

               = 12 \times 2\pi 

               = 24\pi 

Excercise 9:

Using Green’s Theorem evaluate the integral assuming the curve C is oriented Counter clockwise,
\oint_c ln(1 + y) \ dx - \frac{xy}{1 + y} \ dy, where C is the triangle with vertices (0,0), (2,0), (0,4) .

Solution:

greens theorm example 9
greens theorm example 9

The upper bounds for y can be found using points (2,0) and (0,4).

Here,
x_1 = 2, y_1 = 0, x_2 = 0, y_2 = 4,

\frac{y - y_1}{x - x_1} = \frac{y_1 - y_2}{x_1 - x_2} 
             
\frac{y - 0}{x - 2} = \frac{0 - 4}{2 - 0} 

y = -2x + 4 
Using Green’s Theorm,
\oint_c ln(1 + y) \ dx - \frac{xy}{1 + y} \ dy = \iint\limits_R \frac{\delta }{\delta x} (-\frac{xy}{1 + y}) - \frac{\delta }{\delta y} ln(1 + y) \ dA 

                  = \iint\limits_R (-\frac{y}{1 + y} - \frac{1}{1 + y}) \ dA 

                  = \int_0^2 \int_0^{-2x + 4} (-\frac{y}{1 + y} - \frac{1}{1 + y}) \ dy \ dx 

                  = \int_0^2 \int_0^{-2x + 4} -\frac{1 + y}{1 + y} \ dy \ dx 

                  = -1 \int_0^2 \int_0^{-2x + 4} \ dy \ dx 

                  = -1 \int_0^2 [y]_0^{-2x + 4} \ dx 

                  = -1 \int_0^2 -2x + 4 \ dx 

                  = [x^2 - 4x]_0^2 

                  = 4 - 8 - 0 + 0 

                  = -4 

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