Skip to main content

Posts

Showing posts with the label basics

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...

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: Auto completion Syntax Highlighting Code debugger Profilers Multipage editors Auto completion: Auto completion feature suggests APIs [methods, classes and interfaces] and keywords etc as we start typing in the e...

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 J ava 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...

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

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 l...

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 Dem...

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 ...

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){                         ...

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(...

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 mar...

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. Not...

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 c...

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 = ...

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 i...