Posts

Showing posts from May, 2017

TreeEditor: Customizing Drag and Drop

JTree is a Java GUI component for tree structure.  The tree structure is represented by nodes ( DefaultMutableTreeNode ).  The path or the placement of the node in the tree is represented by TreePath . DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); Use TransferHandler for drag and drop.  Supposing a class derived from TransferHandler called MenuTransferHandler handles drag and drop, set the TransferHandler as follows: MenuTransferHandler handler = new MenuTransferHandler(); treeEditor . tree .setTransferHandler(handler); The copied new node should be generated at TransferHandler#createTransferable() .  Here shows the function copy() that may come in handy in writing createTransferable() .   copy() should be called recursively. private DefaultMutableTreeNode copy (TreeNode node) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(node); if (!node.isLeaf()) { @Supp

JPopupMenu

Setting up a right click menu, or popup menu in Java is a tricky but simple procedure.  You would instantiate JPopupMenu, set JMenuItem, attach an ActionListener, set MouseListener.  The beauty of Java GUI structure is in that the listener can be set anywhere.  Any arbitrary component can implement the listener.  A JFrame can have a JPopupMenu and any component can set the MouseListener that set the popup.  And then any component can process the selected JMenuItem. Supposing say a JFrame has a JTable and a JTextArea.  You would want different JPopupMenu.  Each component can possess the JMenuPopup of its own, and the menu can invoke the function in JFrame and not only of JTable nor JTextArea. Which component should have the JPopupMenu (usually the sub-component but can be anywhere) determines what should implements the MouseListener.  The JMenuItem in the JPopupMenu should be 'listened' by an ActionListener that should process the demand. Here is a project that uses a JPop

Quasi Abstraction of the JMenu system

Image
Setting up the menu for JFrame is a matter of creating JMenuBar, JMenu, JMenuItem, add()-ing the components and setting ActionListener for JMenuItem.  The each menu item must be associated with the menu, and the menu must be associated with the menubar.  The ActionListener must be set for each menu item, and the ActionEvent must be processed appropriately. This is a process that can be automated.  It would be far more easier if the menu item can be processed in some managed way.  There are ways of thinking on this: for smaller system, it would be more intuitive if the action is defined in the proximity of the menu item being declared.  In a larger system, it gets unmanageable unless all the accesses are not processed in a centralized manner. →  JavaMenuMenu.java Here I show a way that this procedure can be if not abstracted then greatly simplified by creating a menu class.  Here each menu items is associated with a tag.  A hashtable as the lookup table for the tag and the menu i

TreeEditor: editable tree GUI component

Image
TreeEditor is a Java GUI component for editing tree structure.  It is a JScrollPane (as of TreeEditor ver. 0.1.0) derived and you can directly embed the component in your app.  I would suggest using JSplitPane . First and foremost, load the TreeEditor-0.1.5 library (if you are using Maven) as follows. < dependency > < groupId > com.github.easai.utils </ groupId > < artifactId > TreeEditor </ artifactId > < version > 0.1.6 </ version > </ dependency > Instantiate TreeEditor with a file name (or an empty string).    Initialize it by calling TreeEditor#init() .  Here I put it in a JSplitPane  and the TreeEditor will be resizable as the pane resizes. TreeEditor treeEditor = new TreeEditor( "" ); JTextArea menuCode = new JTextArea(); JTextArea listenerCode = new JTextArea(); public void init () { treeEditor. init (); JSplitPan

Reading RSS in Java

In the previous article, I talked about XML.  It is a hierarchical structure of which each node is represented by <tag> enclosed tags.  The closing tag can either be </tag> or <tag /> format if there is no tags in it. RSS is a type of XML format that consists of pre-defined tags.  Here is how you read RSS feeds.  The structure is simple: the top node is "channel" and the articles are under "item" nodes.  Each "item" node contains nodes such as "title", "description", "link", and so on. The RSS reading code therefore is the same as in the way you read XML files.  I created a library called com.github.easai.text that can simplify the process pretty much.  Using the library, the procedure is abstracted and encapsulated.  So load:   < dependency > < groupId > com.github.easai </ groupId > < artifactId > text </ artifactId > < v

The use of recursive calls

The term "recursive" means in computer science a function call that calls itself, in a way such that you can traverse a tree.  A tree contains nodes and leaves.  You would process the leaves and call the function again for nodes recursively. Consider traversing a directory structure.   File#list() does not list up all the subdirectories.  It is a matter of writing a function that calls itself, i.e., process the files and call the same function for directories. This procedure can be generalized.  Instead of writing the recursive call, here I wrote a class called RecurseDir .  This is an abstract class that calls on the specified file directory recursively. import java.io.File ; public abstract class RecurseDir { /** * Executed on each file. * * @param fileName */ public abstract void executeOnFile ( String fileName ); /** * Executed on each directory. * * @param fileName */ public abstract void

Scheduling jobs with Quartz

Quartz is a Java library that can schdule tasks (using Job derived class).  Let me show how you would use the scheduler.  First, import the library. < dependency > < groupId > org.quartz-scheduler </ groupId > < artifactId > quartz </ artifactId > < version > 2.3.0 </ version > </ dependency > < dependency > < groupId > org.quartz-scheduler </ groupId > < artifactId > quartz-jobs </ artifactId > < version > 2.3.0 </ version > </ dependency > The task that the scheduler runs must be a Job class derivative. import org.quartz.Job ; import org.quartz.JobExecutionContext ; import org.quartz.JobExecutionException ; public class NewsJob implements Job { @Override public void execute ( JobExecutionContext context ) throws JobExecutionException {

Reading JSON with Java

JSON is a "fat-free alternative" of XML format, or the structured dataset format.  Here is a Java code that reads JSON data supplied by a web service.  Replace the URL and perhaps the API key if the site requires it, and the app will parse the JSON response. First of all, edit your POM (pom.xml). < dependency > < groupId > com.github.cliftonlabs </ groupId > < artifactId > json-simple </ artifactId > < version > 2.1.2 </ version > </ dependency > Here is how you can parse the JSON. import java.io.BufferedReader; import java.io.InputStreamReader; import java.net. URL ; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @SuppressWarnings( "deprecation" ) public class NewsApp { public static void main( String args[]) { JSONParser parser = new JSONParser(); Strin

Parsing XML file with DOM

There are ways in Java how you can read or write  XML files.  Here is a way of reading and writing a XML file using DOM. The function readXML() reads the specified file.  It does all the preliminary works for reading an XML file.  It creates DocumentBuilderFactory , DocumentBuilder , and Document .  The XML file will be read by calling DocumentBuilder#parse(). The parseXMLTree() function recursively parses the DOM tree.  It outputs the text contents of each <value> tag of the node.  A word of caution: it is not Node#getNodeValue() that retrieves the text content of the node.  Call Node#getTextContent() instead. The function writeXML() does all the work for writing out the XML.  It creates TransformerFactor , Transformer , and DOMSource .  The StreamResult object creates the stream for the specified file.  Finally, call Transformer#transform() and it will write out the XML. import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; imp

Command line options with command-cli

How do you use command line arguments in Java?  The Java SDK does not come with library that can parse the arguments.  Parsing each argument is a tedious work, however. The common-cli does the all the work for you.  The library can parse the input for short and long versions of the command line input.  The "-f" option should be the same with "--trefile" , that is.  The options can be optional or mandatory.  If the required option is not there, it will print out the usage as specified.  Nice, is it?  It only is a matter of editing the pom.xml .  Here you go:   < dependency > < groupId > commons-cli </ groupId > < artifactId > commons-cli </ artifactId > < version > 1.4 </ version > </ dependency > As for parsing the input arguments, set the Option and parse the command line with CommandLineParser with the option settings.  If any wrong option is set, the usage will be printed by HelpFormatte

Logging your Maven project with Logback

How do you trace your app?  Well, simple standard output is enough for simple applications.   What if, however, you'd want layered commeting/tracing?  Supposing, say, you do not want lengthy trace info for regular use of your app?  The error reports certainly should be distinguished from debugging info. Logback is a nice package that does the work.  Your app will emit any sort of messages, with proper labels (error, warning, info, debug, trace).  Load the library by editing pom.xml file.   < dependency > < groupId > ch.qos.logback </ groupId > < artifactId > logback-classic </ artifactId > < version > 1.2.2 </ version > </ dependency > The log file should be specified in logback.xml file.  The file should be under src/main/resources.   <? xml version = "1.0" encoding = "UTF-8" ?> <! DOCTYPE logback > < configuration > &

Java library management with Maven and Gradle

In the last blog, I showed you some of the cases that uses the library in the Central Repository with Maven.  In the following test cases, I show you how the library can be incorporated into your project by using Maven ( ComplexMaven ) and Gradle ( ComplexGradle ).  The projects uses the library called Complex .  Complex is available from the Central Repository.  Maven and Gradle use different configuration files for library dependency. In case with Maven, the library dependency is in the pom.xml file (POM file).  The file format goes as folllows:   < dependency > < groupId > com.github.easai.math </ groupId > < artifactId > Complex </ artifactId > < version > 0.0.1 </ version > </ dependency > If you are using Gradle, the configuration should be in the build.gradle file.   compile group: 'com.github.easai.math', name : 'Complex', version :' 0.0 . 1 

Java library management with Maven

Using Maven, the library management is as intuitive as it could ever be.  "DLL hell" headache is over by specifying the version of the library in the project pom.xml file.  Furthermore, all JAR files are managed and stored locally as any requests are made by the project. Maven configuration is specified in a file called POM, specified in pom.xml.  This XML formatted file specify all that the compiler would need, including the package configuration and libraries. If you are not using Maven and copying the Complex library JAR file into your project library, the library management is manual.  Which means, you would have the same copy of the JAR files all over the place for whichever project that needs it.  If the library is updated, you would download the updated file for all the projects that use the library. Supposing you have Complex library and your projects Mandelbrot and Misiurewicz  need that library. Using Maven, incorporating that library is as simple as it coul