It's all about Java: basics
Showing posts with label basics. Show all posts
Showing posts with label basics. Show all posts

Thursday, 22 April 2021

Java programming language and IDEs

IDE: Integrated Development Environment

Integrated development environment, in short IDE is a convenient environment to write, execute and  debug the code or programs on a single platform. IDEs support not only writing code smoothly but also provides a provision to write scripts, XML files, simple text files and build scripts like Ant, Maven are few among others.

In short IDEs are development environments to execute complete development activities using one application.


IDEs and Editors

IDEs and Editors fulfills the same purpose. That is writing code. But IDEs are glued or closely works with respective programming language's compilers, runtime environments, profilers and other language specific tools to put developer in a comfortable zone. 

Some of the features of IDE:
  1. Auto completion
  2. Syntax Highlighting
  3. Code debugger
  4. Profilers
  5. Multipage editors

Auto completion:

Auto completion feature suggests APIs [methods, classes and interfaces] and keywords etc as we start typing in the editor. This helps in not spending much time on typing APIs.




Syntax Highlighting:

Syntax is a structure of arranging APIs, operators and keywords to make computer instructions, subsequently which becomes executables.

Class names, method names, operators and Keywords are highlighted with different colors and formats to differentiate them and to increase the readability. Syntax highlighting helps importantly when single program or file has thousands of statements or lines.

Code Debugger:

Debugger is a feature to identify bugs, errors and shows intermittent results of set of programming instructions or statements and subsequently helps in correcting and developing a bug free computer programs






Profilers:

Profiler is the tool usually shipped along with JDK [if it is a Java] and helps in understanding the memory usage of a computer application graphically. These graphics includes different charts and GUI controls. 



Profilers gives information about

  •  Memory usage,
  •  details of Threads being used,
  •  Heap dumps,
  •  CPU utilization etc

Multipage Editors:

Multipage editors shows the same file content in multiple perceptions. For example XML file content can be viewed in different views. 1. Hierarchical view 2. Simple text format and 3. Graphical view etc


  


Few more notable points about IDEs and Editors:

  1. IDEs are scalable to support multiple programming languages
  2. Editors can not be glued to a programming language's compiler
  3. Editors does not support Auto completion
  4. Editors does not support code debugging
 

IDEs for Java and IDEs built using Java

Usually IDEs are developed using different programming languages where, few of them are open source and few are commercial. Few of the industry endorsed IDEs are:

  • Eclipse
  • Netbeans
The above listed IDEs are developed using Java programming language and also used to develop Java applications and programs. It is little tricky to understand for beginners. 
And both IDEs share common features like scalability, modularity, code completion etc.
You can download Eclipse and Netbeans distributions from their respective sites.


Happy Coding! :)

Monday, 29 January 2018

Swing: JFrame usage demo

This post helps in understanding usage of JFrame class with an example


Swing toolkit categorizes components into 2 types. They are:

  • Containers
  • Controls

Containers allows Controls to be arranged on them. JPanel, JFrame and JDialog are few which are frequently used.

Controls are components like Buttons, labels, tables etc. These controls are arranged on containers using different layout managers.

All Swing class names starts with J stands for Java which symbolizes swing is pure java! 

Layout Managers:

Layout manager is responsible for laying out controls on containers according to the business requirement. Example layout managers are BorderLayout, GridLayout, GridBagLayout and FlowLayout.

Few points about JFrame:
  • JFrame is considered as a main window of the application.for almost all swing based applications
  • All other controls and containers are created as child components of JFrame
  • JFrama holds special components like  Menu bar, Tool bar etc  

Example program

1 import javax.swing.JFrame;
2 import javax.swing.SwingUtilities;
3
4 /**
5  *
6  * Simple class to demonstrate JFrame container of swing toolkit
7  *
8  * @author Nagasharath
9  *
10 */
11public class FrameDemo extends JFrame {
12
13 private final String title = "It's all abt java!...  ";
14
15 /**
16 * set properties of the main window. Title, size of frame and position/location
17 */
18 public FrameDemo() {
19 this.setTitle(title);
20 this.setSize(300, 200);
21 this.setLocationRelativeTo(null);
22 initComponents();
23 }
24
25 /**
26 * It is used in future articles for instantiating controls like buttons etc.
27 * left empty for now.
28 */
29 private void initComponents() {
30 }
31
32 public static void main(String[] args) {
33
34 Runnable r = () -> {
35 FrameDemo demo = new FrameDemo();
36 demo.setVisible(true);
37 };
38 SwingUtilities.invokeLater(r);
39 }
40}
41


Line 1: Our class FrameDemo extends JFrame hence gets all benefits that JFrame possess    

Line 20: Sets the width 300 and height 200. How ever frame is re sizable at run time

Line 21:  Puts the frame at the center of the desktop monitor

Line 36: Unless call to setVisible(true), frame can not be seen at all.

Line 38: It is always good practice to call setVisible(true) in invokeLater().

Output on Win 10:

The look and feel we see below  is default which is same on all platforms 

This Look and feel can be changed using UIManager class. We see it in coming posts.  

      
JFrame with title


Sunday, 28 January 2018

Java Multi threaded programming basics with Reentrant lock

Java Multi threaded programming basics with Reentrant locks

As we have seen in earlier post that implicit locking mechanism achieved using synchronized keyword slows down the application performance. Hence java concurrency api gives explicit locking mechanism to achieve mutual exclusion among shared object.

How using explicit locks are better than implicit lock?


  • Explicit lock acquires lock per Thread basis and not per method invoke basis. It is inverse in the case of implicit lock.  
  • If a method is synchronized then every invocation of that method involves acquiring and releasing of lock. This process really slows down the application performance. 
  • Hence it is always good idea to prefer reentrent lock or explicit lock to implicit lock.
  • ReentrantLock is a class available in java.util.concurrency package
  • lock() and unlock() methods are used used to acquire and release the lock.
  • Condition class is used in place of Object class wait(), notifyAll() and notify().
  • signal() and await() of Condtion are used mostly 
Let's see the  Java Multi threaded programming basics Producer and Consumer Problem's solution with Reentrent lock.


import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * In {@code BufferImpl} we have seen thread safe 
 * buffer implementation using implicit lock/ synchronization block
 * 
 * This {@code BufferImpl_conc} we see same implementation replacing implicit
 * lock with concurrency utility classes Reentrant Locks
 * 
 * Buffer implementation with ArrayList and with Producer consumer 
 * problem implementation
 * 
 * @author Nagasharath
 *
 */
public class BufferImpl_conc {

   private CopyOnWriteArrayList<String> buffer;
   private final short SIZE = 10;
   private boolean isBufferFull = false;
   private ReentrantLock lock;
   private Condition condition;

  public BufferImpl_conc() {
     buffer = new CopyOnWriteArrayList<String>();
     lock = new ReentrantLock();
     condition = lock.newCondition();
  }

 /**
  * @throws InterruptedException
  */
 private void producesFeed() throws InterruptedException {
    lock.lock();
    try {
       while (true) {
         if (isBufferFull) {
             System.out.println("Started Consuming!....\n");
             condition.signal();
             condition.await();
        }
        buffer.add(String.valueOf(System.nanoTime()));
        if (SIZE <= buffer.size()) {
              isBufferFull = true;
              Thread.sleep(10000);
              System.out.println("Buffer full. Production halts...\n");
       }
     }
    } finally {
        lock.unlock();
    }
 }

 /**
  * @throws InterruptedException
  */
 private void consumesFeed() throws InterruptedException {
    lock.lock();
    try {
       while (true) {
          Iterator<String> iter = buffer.iterator();
          while (iter.hasNext()) {
             String next = iter.next();
             System.out.println("Consuming element: " + next);
             buffer.remove(buffer.indexOf(next));
          }
          isBufferFull = false;
          System.out.println("Started producing!....");
          condition.signal();
          condition.await();
      }
   } finally {
      lock.unlock();
   }
 }
 /**
  * @author Nagasharath
  *
  */
 class ProducerThread extends Thread {
     @Override
    public void run() {
      try {
        producesFeed();
      } catch (InterruptedException e) {
      }
  }
 }

 /**
  * @author Nagasharath
  *
  */
 class ConsumerThread extends Thread {
  @Override
  public void run() {
    try {
      consumesFeed();
    } catch (InterruptedException e) {
    }
  }
 }
 public static void main(String[] args) {
   BufferImpl_conc impl = new BufferImpl_conc();
   ProducerThread producerThread = impl.new ProducerThread();
   ConsumerThread consumerThread = impl.new ConsumerThread();
   producerThread.start();
   consumerThread.start();
 }
}

Most parts of the program are same as we used in the post Java Multi threaded programming basics It is advised to read my post  Java Multi threaded programming basics before reading this. I try to explain changes from earlier post program here

  1 private final short SIZE = 10;
  2 private boolean isBufferFull = false;
  3 private ReentrantLock lock;
  4 private Condition condition;

Line 3: Instance of ReentrantLock is similar to synchronized keyword locking but it is more intelligent.
Line 4: Condition instance has methods which replaces Object class wait and notify() methods.

  1  public BufferImpl_conc() {
  2     buffer = new CopyOnWriteArrayList<String>();
  3     lock = new ReentrantLock();
  4     condition = lock.newCondition();
  5  }
Line 3 and Line 4: Instantiates lock and condition Objects

 1 private void producesFeed() throws InterruptedException {
 2   lock.lock();
 3    try {
 4      while (true) {
 5         if (isBufferFull) {
 6             System.out.println("Started Consuming!....\n");
 7             condition.signal();
 8             condition.await();
 9         }
 10         buffer.add(String.valueOf(System.nanoTime()));
 11         if (SIZE <= buffer.size()) {
 12           isBufferFull = true;
 13           Thread.sleep(10000);
 14           System.out.println("Buffer full. Production halts...\n");
 15         }
 16       }
 17     } finally {
 18          lock.unlock();
 19     }
 20 }
Line 1: await() at line 8 throws InterruptedException
Line 2: lock.lock() statement is equal to the synchronized(this)  {  . . .  }
Line 7: condition.signal() notifies the waiting thread on same object to start it's execution
Line 8: condition.await() makes current thread to wait on isBufferFull == true condition check
Line 17 to Line 19: lock.unlock() must be called in finally block always

Output:  


Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838231927112595
Consuming element: 2838231927212435
Consuming element: 2838231927229502
Consuming element: 2838231927238888
Consuming element: 2838231927246995
Consuming element: 2838231927254675
Consuming element: 2838231927261075
Consuming element: 2838231927267902
Consuming element: 2838231927274302
Consuming element: 2838231927281555
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838242029132348
Consuming element: 2838242029210428
Consuming element: 2838242029244561
Consuming element: 2838242029271015
Consuming element: 2838242029386215
Consuming element: 2838242029448935
Consuming element: 2838242029479228
Consuming element: 2838242029504401
Consuming element: 2838242029529148
Consuming element: 2838242029553895
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838252029524881
Consuming element: 2838252029547921
Consuming element: 2838252029556881
Consuming element: 2838252029563281
Consuming element: 2838252029568401
Consuming element: 2838252029573521
Consuming element: 2838252029578215
Consuming element: 2838252029582908
Consuming element: 2838252029588028
Consuming element: 2838252029593148
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838262032106639
Consuming element: 2838262032149732
Consuming element: 2838262032165092
Consuming element: 2838262032193252
Consuming element: 2838262032204772
Consuming element: 2838262032214585
Consuming element: 2838262032223972
Consuming element: 2838262032233359
Consuming element: 2838262032241892
Consuming element: 2838262032251279
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838272040024285
Consuming element: 2838272040065245
Consuming element: 2838272040077619
Consuming element: 2838272040086152
Consuming element: 2838272040093832
Consuming element: 2838272040101512
Consuming element: 2838272040108766
Consuming element: 2838272040115592
Consuming element: 2838272040122845
Consuming element: 2838272040130099
Started producing!....

 

Java desktop GUI.

Graphical user interface in short GUI makes computer users easy to understand and use the application software comfortably. Almost all modern programming languages allows application developers to develop GUIs.

Java has AWT/Swing as default API as part of Java Foundation classes in short JFC which are shipped with JDK. Hence these toolkits can be used directly in our applications with out adding external libraries like jars to our application's class path. But there are some other toolkits which found useful and industry endorsed in developing GUI.

    •      SWT 
    •      JFaces [Framework for SWT]
    •      Java FX
    •      Swing
    •      AWT

AWT:

Abstract window toolkit is available since java first version. AWT uses native operating system resources like Fonts, colors and components like table, tree, dialogues, windows etc.

Few notable points about AWT:
  • AWT is heavy weight. It uses OS resources
  • There are limited components in AWT precisely only components which are available in native OS. 
  • We can not have a new component according to our business logic need. ex: Tri state checkbox or treetable  
  • AWT behaves differently on different platforms
  • Hence it violates the java Platform independence rule
  • The program GUI developed with AWT looks differently on different OSs. Means on linux it renders linux graphics look and feel and on windows platform it renders windows graphics look and feel.   
  • Provides event model API which also used by Swing toolkit

Swing:

  • Swing was designed and developed keeping all cons in mind that are caused due to using AWT toolkit.
  • First of all "Swing is pure java hence it is platform independent." This statement made many good things possible:
Few notable points about Swing:
  •  Swing is light weight. It does not depend on native OS resources 
  •  Unlike AWT, it is extensible. New custom components can be developed according to program  requirement. 
   NOTE: See swingx library in it's official site.
  •  Swing has Pluggable look-and-feel support in short PLAF.
  •  Drag and Drop api, 2D api, internationalization are few among other included in Swing toolkit.
  •  Netbeans IDE itself is a good example for swing based application used allot now a days.
  •  Few GUI experts noticed that Swing is slow and not quite professional for commercial applications

SWT:

Standard Widget toolkit in short SWT is another toolkit for developing Java Desktop GUI based applications.
Compared to Swing it is faster and consistent in performance and Eclipse IDE itself is an example for SWT based applications.
Eclipse is industry endorsed IDE specifically for java based software development.
This is not shipped with JDK. Please see eclipse.org [official site] for more details.
And there are Integrated development environments in short IDE which provides Drag and Drop [DAD] palettes also known as GUI Builders for above toolkits for programmer's convenience.
Mostly used IDEs are:
It is advised to code manually to develop the GUI rather using GUI builders provided by different IDEs. And for beginners.  


Sunday, 21 January 2018

CHEAT SHEET for java List interface, LinkedList and ArrayList

Consider Below points before choosing List concrete implementations for your use case: 

  • ArrayList is a linear data structure and  re-sizable/dynamic array
 
  • Initial size can be given. and if not given the default size is 10
 
  • It is always good practice to give initial size and advised not to give very large number as size
 
  • Good programmers prefer ArrayList to LinkedList if retrieval operations is done more frequently than insertion and deletions of elements.
 
  • Better choose LinkedList if insertion and deletion operations are done frequently compared to retrieval operations.
 
  • Lists are not sorted. if required use Collections.sort() to sort
 
  • Collections.sort() uses optimized merge sort [tim sort] on ArrayList
 
  • However legacy merge sort also can be used using a switch. But it is going to be deprecated  in near future 

  • The major difference between ArrayList and LinkedList is RandomAccess behavior 

  • ArrayLists uses Random access indexing where as LinkedLists uses
          Sequential access indexing
 
  • LinkedList carries extra overhead in the form of reference to the next and previous elements other than element's data itself

  • LinkedList uses Doubly LinkedList data structure internally

  • Deque is the java DoubleLinkedList data structure implementation

  • Before choosing List implementation ask yourself below questions 
                    a. Are you aware of initial size? 
                    b. Which operations are used more frequently? [insertion, deletion,
                       retrieval, search, sort are few among others]

  • Search Algorithm: 
                  a. Collections class uses binary search if List is ArrayList
                  b. Collections class uses linear search if List is of type LinkedList


  • ArrayList and LinkedList both uses fast fail iterations.

  • If another thread tries to modify list while iterating, java runtime throws ConcurrentModificationException. This can be considered as fast fail behavior  

Saturday, 30 December 2017

Simple program which demonstrates Swing/AWT Grid layout

Simple program which demonstrates Swing/AWT Grid layout:


This post is intended to the beginners of swing/awt.

This below program creates a JFrame with 2 labels, 2 textfields and 2 buttons.


import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 * @author Nagasharath Kopalle
 *
 * Simple program to demontrate Gridlayout
 *
 */
public class GridLayoutDemo extends JFrame {

private JLabel labelName = null;

private JTextField textFieldName = null;

private JLabel labelPassword = null;

private JPasswordField passwordFieldPassword = null;

private JButton buttonSubmit = null;

private JButton buttonCancel = null;

/**
*
*/
public GridLayoutDemo() {
initComponents();
}

/**
* instantiates components and adds properties.
*/
void initComponents() {

this.setTitle("Grid Layout Demo");
this.setSize(300, 200);
GridLayout layout = new GridLayout(3, 2);
layout.setHgap(10);
layout.setVgap(5);
labelName = new JLabel("User Name: ");
textFieldName = new JTextField();

labelPassword = new JLabel("Password: ");
passwordFieldPassword = new JPasswordField();

buttonSubmit = new JButton("Submit");
buttonCancel = new JButton("Cancel");

this.setLayout(layout);
this.getContentPane().add(labelName);
this.getContentPane().add(textFieldName);

this.getContentPane().add(labelPassword);
this.getContentPane().add(passwordFieldPassword);

this.getContentPane().add(buttonSubmit);
this.getContentPane().add(buttonCancel);
}

public static void main(String[] args) {

GridLayoutDemo demo = new GridLayoutDemo();
demo.setVisible(true);
}
}

Output:


Sunday, 29 October 2017

Eclipse Java Editor Shortcuts

Eclipse Oxygen Java editor Shortcuts helps in editing source code more comfortably. Frequently used default shortcuts are listed below. 




Description
Shortcut
Delete Line
CTRL + D
Copy Line
CTRL + ALT + Down Arrow
Add method level, class level, member level Comments
SHIFT + ALT + J
Format Java Source code
CTRL + SHIFT + F
Make line commented
CTRL + /
Make multiple lines [block] commented  
CTRL + SHIFT + /
Search selected similar word within the source document
CTRL + K
Select line from beginning to end
SHIFT + End key
Select line from end to beginning
SHIFT + Home key
Select Word by word in same line
CTRL + SHIFT + Right Arrow
Move line above
ALT + Up Arrow
Move line below
ALT + Down Arrow

Shortcuts can be customized and new shortcuts can be created through Keys Page in Preferences wizard.


  1.  Window menu > Go To Preferences 
  2.  Type Keys as the "filter text"
  3.  Please find the image below for reference.


Example:
Add new Shortcut for cut whole line command.

  1.  In Keys page type filter text -- Cut line
  2.  Type your convenient key. In my case I added SHIFT + X
  3.  Finally, Click Apply and Click Apply and Close.
  4.  That's it. Now Test your new Shortcut. 

Happy Coding :)

Saturday, 21 October 2017

Launch Swing GUI always in a dedicated Thread



1. Since Swing is not thread safe, it is not at all a good practice to launch a UI Container like JFrame, JDialog etc in main Thread.
2. Doing so leads to incorrect behavior of java GUI.
3. To avoid this, Swing toolkit has predefined API as part of JFC.
4.    a. SwingUtilities.invokeAndWait(Runnable r);
       b. SwingUtilities.invokeLater(Runnable r);

5. Which part of the code must be in UI Thread?
        a. setVisible(true);
        b. show(); [deprecated]
 and c. pack();
     

6. Call to these methods mentioned in 5(a), 5(b), and 5(c) must happen in one of the methods mentioned in point 4(a) and point 4(b). That's enough. :)
         Example :
             
         public static void main(String[] args){
                         
         JFrame frame = new JFrame();
         frame.setSize(100, 200);
         SwingUtilities.invokeAndWait(new Runnable(){
             public void run(){
                     frame.setVisible(true);
                     frame.pack();
             }//run
        });//
       }//main

  7. Difference between invokeAndWait() and invokeLater():
          a. invokeLater() is non blocking and asynchronous, where as invokeAndWait() is blocking and synchronous.
          b. Since invokeLater() is asynchronous, It is more flexible.
                                 
                                   

Friday, 6 October 2017

File Manager/File Explorer with Swing JTree Component

This post is intended to beginners of java swing toolkit programmers.
It is a simple java program which demonstrates the swing based File explorer GUI.





import java.awt.GridLayout;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * @author NagasharathK
 *
 */
public class FileExplorer extends JFrame {

private JTree fileManagerTree = null;

public FileExplorer() {
initComponents();
}

/**
* Initializes components
*/
private void initComponents() {
this.getContentPane().add(new JScrollPane(createFileManagerTree()));
this.setSize(500, 500);
this.setResizable(true);
this.setTitle("File Manager..");
}

/**
* @return JPanel object which contains other comp...
*/
private JPanel createFileManagerTree() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());

fileManagerTree = new JTree();
fileManagerTree.setModel(new FilesContentProvider("C:\\"));
panel.add(fileManagerTree);
return panel;
}

class FilesContentProvider implements TreeModel {

private File node;

public FilesContentProvider(String path) {
node = new File(path);

}

@Override
public void addTreeModelListener(TreeModelListener l) {

}

@Override
public Object getChild(Object parent, int index) {
if (parent == null)
return null;
return ((File) parent).listFiles()[index];
}

@Override
public int getChildCount(Object parent) {
if (parent == null)
return 0;
return (((File) parent).listFiles() != null) ? ((File) parent).listFiles().length : 0;
}

@Override
public int getIndexOfChild(Object parent, Object child) {
List<File> list = Arrays.asList(((File) parent).listFiles());
return list.indexOf(child);
}

@Override
public Object getRoot() {
return node;
}

@Override
public boolean isLeaf(Object node) {
return ((File) node).isFile();
}

@Override
public void removeTreeModelListener(TreeModelListener l) {

}

@Override
public void valueForPathChanged(TreePath path, Object newValue) {

}

}

/**
* @param args
* @throws InvocationTargetException
* @throws InterruptedException
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws InvocationTargetException, InterruptedException,
ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
FileExplorer explorerUI = new FileExplorer();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
explorerUI.setVisible(true);
}
});
}
}
 

The above program has one inner class [FilesContentProvider] which serves as a model to the JTree.

The UI has 4 Components: JFrame, JScrollPane, JPanel and JTree.

To Do:

  1. Add Context menu to node based upon the file type
  2. Add Cell renderer to give proper names to the Nodes
  3. Option to Expand whole tree or selected node etc..  


Friday, 6 January 2017

GridLayout: fill the form with gridlayout

Swing controls are of two types they are Containers and components. components are arranged on a containers. example components are JLabel, JButton etc and example containers are JPanel, JFrame and JDialog etc.
these components are arranged on a container with the help of layout managers. Few layout managers available in swing toolkit are

1. FlowLayout [Jframe's Default layout manager]
2. GridLayout
3. BorderLayout [JPanel's Default layout manager]
4. GridBagLayout.
5. Custom Layout manager

The custom layout amanger is useful to design programmer's own layout manager. Usually this is useful when any of the available layout managers does not give the needy result.
apart of these above all layout managers, few third party libraries are also available they are

1. DesignGridLayout
2. Mig Layout etc

Design grid Layout


Gridlayout is one of the most simple and flexible layout managers. layout manager is used to arrange the components on a container with proper margins, gap etc.

Gridlayout is suitable when the number of components are even numbered in each row of the container.


Swing program without any layout manager:


import java.awt.GridLayout;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GridLayoutExample extends JFrame {

private JLabel label1 = null;
    private JLabel label2 = null;
    private JLabel label3 = null;
    private JTextField tf1 = null;
    private JTextField tf2 = null;
    private JTextField tf3 = null;
    private JButton button1 = null;
    private JButton button2 = null;

    public GridLayoutExample() {
        initComponents();
    }

    private void initComponents() {

        label1 = new JLabel("Name: ");
        add(label1);
        tf1 = new JTextField();
        add(tf1);

        label2 = new JLabel("Qualification: ");
        add(label2);

        tf2 = new JTextField();
        add(tf2);
        label3 = new JLabel("Profile: ");
        add(label3);

        tf3 = new JTextField();
        add(tf3);

        button1 = new JButton("Submit");
        add(button1);
        button2 = new JButton("Cancel");
        add(button2);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
    }


    public static void main(String[] args) throws InvocationTargetException, InterruptedException {

        GridLayoutExample ex = new GridLayoutExample();

        ex.setSize(300, 200);
        ex.setLocationRelativeTo(null);
        
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                ex.setVisible(true);
            }
        });

    }
}

  Output:





Shown below is a Swing program after adding a GridLayout. 

Replace the initComponents() of the above program with the below method


   private void initComponents() {
    GridLayout gl = new GridLayout();
    gl.setColumns(2);
    gl.setRows(4);
    gl.setHgap(15);
    gl.setVgap(15);

    this.setLayout(gl);

    label1 = new JLabel("Name: ");
    add(label1);
    tf1 = new JTextField();
    add(tf1);

    label2 = new JLabel("Qualification: ");
    add(label2);

    tf2 = new JTextField();
    add(tf2);
    label3 = new JLabel("Profile: ");
    add(label3);

    tf3 = new JTextField();
    add(tf3);

    button1 = new JButton("Submit");
    add(button1);
    button2 = new JButton("Cancel");
    add(button2);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
}



the output after applying layout manager.....







Tuesday, 27 December 2016

WMI - Windows Management Instrumentaion

WMI is a windows Library used to get the information like no of processes running currently in the computer and their event notifications like process creation modification and deletion notifications, cumputer's name, version, Win32 processes list etc

The information above mentioned can be fetched not only from local PC but also the remote machine too..

WMI can be accessed through a query langauge in two ways they are:

1. WBEMTEST.exe [GUI Tool]
2  WMIC- stands for WMI Commandline tool
3. Programatically [using Powershell and VBScript]


1. wbemtest.exe:



      How to start

         1. go to start
     
         2.  go to Run
       
         3. Type wbemtest.exe
       
         4.  the following window opens up.



Queries that can be run with this tool

1. Usual queries
2. Notification queries

Usual queries are used to query the processes and other system information etc. the query fetches the information from repository and ends the task.

Example Query:

SELECT * From Win32_Process

the above syntax fetches the current running Win32 process.




Notification queries are those which runs continuously and gives the notification of Process creation, modification and deletion and returns the object through which process information can be fetched accordingly.

Example Query:

SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'

the above query notifies us whenever an existing process is deleted. WITHIN clause checks the condition for every 1 second. this query needs to be executed in Notification Query window. please refer the above figure.

 SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'

This above query notifies when new process is created


2. WMIC.exe

The second approach for accessing WMI is WMIC.exe which is a command line tool.

1. goto start
2. goto Run
3. open the CMD.exe
4. type wmic.exe



the above steps opens up the wmic command line tool where we can fetch OS, Processes, memory information and many more :) details of a PC.



Example command

 Process List

the Process list command lists the all the processes running currently in local machine.


Apart of these tools we can access the WMI through programs too using VBScript and Powershell.


Happy Coding! :)





Monday, 26 December 2016

Apache Commons Exec API for executing exe files from java program

In my previous post http://java-gui.blogspot.in/2016/12/api-for-executing-exe-files-from-java.html    you have seen using traditional java API to execute exe files from java program.

but it is proved that it is not an ideal solution for  programs which handles IO operations and for async executables. you can find more advantages of Apache Commons Exec library over traditional API in the below link.

              http://commons.apache.org/proper/commons-exec/index.html


Simple example that uses the Exec library:

// class to pass the command ex: cmd.exe and its arguments...

CommandLine command = new CommandLine("ping");

// arguments to the command object can be passed in 2 ways...

command.addArguments("localhost") ;
command.addArguments("-t") ;
command.addArguments("-count");

   or

command.addArguments(new String[]{"-t", "-count"});


//handling the IO operations gracefully using LogOutputStream abstract class


LogOutputStream in = new LogOutputStream() {

@Override
protected void processLine(String line, int exitvalue) {

                       //handle the output which was produced by the process....
                      System.out.println(line);
               }
};
PumpStreamHandler streamHandler = new PumpStreamHandler(in, in);

// Executing the command along with its arguments

DefaultExecutor executor = new DefaultExecutor();

//attaching the created shreamhandler to the executor...

executor.setStreamHandler(streamHandler);

// execution...
executor.execute(command);


the above program executes the ping command and displays the output using the standard out.

Executing the interactive executables can be found in the below link...


link


API for executing exe files from java program.

The traditional API for calling the executable in java program is using the Runtime, Process and their methods like exec(command), waitFor() methods respectively.

a simple example to execute a notepad.exe from java program using the above API is given below.

Process process = Runtime.getRuntime().exec("notepad.exe");

the above code is used to launch the notepad.exe executable from java program.


if there are multiple commands needs to be passed then the code would be....

String[] command = {"cmd.exe", "/C", "echo ", "%TEMP%"}; 
Process process = Runtime.getRuntime().exec(command);

the above snippet is used to execute multiple commands in a java program. this code prints the environment variable TEMP on to the console.


Handling standard output produced by the above code:

BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
String line = "";

while((line = input.readLine()) != null){

System.out.println(line);

}

This Procedure is ideal when there is an executable to run without waiting for its completion of execution. despite the a method called p.waitFor() which waits until the process execution is completed, it is difficult to handle the process's standard Outputs and Inputs gracefully. and the no of lines of code also increases drastically.

the alternative to this traditional API is Apache Commons Exec  library.




Saturday, 23 July 2011

JForm: Fill the form with style

After understanding and using swing toolkit, I understood that there is a allot of scope to develop Custom components easily.
I have developed a component called JForm which basically a button and its selection pops up a window if it is not visible.

Technically the JForm component is a combination of 2 components they are:

1. JButton
2. Window

JButton is a API of swing toolkit where as Window is a API of AWT.

Behaviour of JForm:

JForm is a usual button like JButton. but it is glued to a Window component. this Window takes a JPanel class as an arguments.

In the given example has 2 components they are 1. JTextArea  2. JButton [Submit] which are appended to a JPanel..

The below image shows the effect before selecting the JForm:






This image shown is the effect after selecting the JForm:

                                     



the below code is an example which includes code for JForm custom component and main() includes usage of JForm.


import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class JForm extends JButton {

Point location;
int X = 0;
int Y = 0;
int W = 0;
int H = 0;
JFrame frame;
MyWindow window;

public JForm(JFrame frame, JPanel panel) {

this.frame = frame;
this.setBackground(Color.gray);
this.setText("click me!...");
JForm.this.window = new MyWindow();
JForm.this.window.add(panel);
this.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

if (window.isVisible() == false) {
JForm.this.window.setSize(10, 20);
location = getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
window.pack();
window.setVisible(true);
}else{
window.setVisible(false);
}
}
});
}

class MyWindow extends Window {
public MyWindow() {
super(JForm.this.frame);
frame.addComponentListener(new ComponentListener() {
public void componentResized(ComponentEvent evt) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}

@Override
public void componentHidden(ComponentEvent arg0) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}

@Override
public void componentMoved(ComponentEvent arg0) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}

@Override
public void componentShown(ComponentEvent arg0) {
if (JForm.this.isShowing() == true) {
location = JForm.this.getLocationOnScreen();
X = location.x;
Y = location.y;
JForm.this.window.setLocation(X - 5, Y + JForm.this.getHeight());
}
}
});
}

}

public static void main(String[] args) {
JFrame frame = new JFrame();

GridBagLayout l = new GridBagLayout();

GridBagConstraints c = new GridBagConstraints();
c.gridwidth = 40;
c.gridheight = 20;
frame.setLayout(l);
JPanel panel = new JPanel();
GridBagLayout pl = new GridBagLayout();
GridBagConstraints pC = new GridBagConstraints();
JTextArea ta = new JTextArea(5, 10);
panel.add(ta, pC);
JButton button = new JButton("Submit");
pC.gridx = 50;
pC.gridy = 40;
panel.add(button, pC);

panel.setBackground(Color.gray);
JForm form = new JForm(frame, panel);
l.setConstraints(form, c);
frame.getContentPane().add(form, c);
frame.setSize(200, 200);
frame.pack();
frame.setVisible(true);
}
}

Next time I will come up with a JForm with different shapes like rounded, rounded corners etc..  

Popular posts

Atomicity with Java Programming Language

 Atomicity with Java What is Atomicity Atomicity, in computer science, is considered to be a property [ALL-OR-NOTHING], that the state of a ...