James Gosling: idealism, the Internet and Java, Pt I

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

Friday 22 July 2011

JColorComboBox: JComboBox as Color Chooser

 
Swing toolkit provides a component called JColorChooser to choose colors. It allows users to select color from multiple color combinations. Some times our application may need simple component with an option to select only basic colors/ less number of color options unlike sepearate dialog with too may color options[JColorChooser]. This JColorComboBox may serve the need.

I wanted my color chooser to behave like JComboBox. The popup shows all 12 colors and their names, among all of them one color can be choosen. see the below image.


I created two classes
         1. JColorComboBox
         2. ColorRenderer
JColorComboBox extends the JComboBox and ColorRenderer extends JLabel and implements ListCellRenderer.


import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.*;
/**
*
* @author sharath
*/
public class JColorComboBox extends JComboBox {

static Hashtable<String, Color> colors;

public JColorComboBox() {
super();
DefaultComboBoxModel model = new DefaultComboBoxModel();
Enumeration colorNames = addColors().keys();
while(colorNames.hasMoreElements()){
String temp = colorNames.nextElement().toString();
model.addElement(temp);
System.out.println("colors"+temp);
}
setModel(model);
setRenderer(new ColorRenderer());
this.setOpaque(true);
this.setSelectedIndex(0);
}
@Override
public void setSelectedItem(Object anObject) {
super.setSelectedItem(anObject);

setBackground((Color)colors.get(anObject));
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
if(anObject.toString().equals("BLACK") || anObject.toString().equals("DARK_GRAY")){
setForeground(Color.white);
}
}
public Color getSelectedColor(){

return this.getBackground();
} 

private Hashtable addColors(){

colors = new <String, Color>Hashtable();

colors.put("WHITE", Color.WHITE);
colors.put("BLUE", Color.BLUE);
colors.put("GREEN", Color.GREEN);
colors.put("YELLOW", Color.YELLOW);
colors.put("ORANGE", Color.ORANGE);
colors.put("CYAN", Color.CYAN);
colors.put("DARK_GRAY", Color.DARK_GRAY);
colors.put("GRAY", Color.GRAY);
colors.put("RED", Color.RED);
colors.put("PINK",Color.PINK);
colors.put("MAGENTA", Color.MAGENTA);
colors.put("BLACK", Color.BLACK);

return colors;
}
 
class ColorRenderer extends JLabel implements javax.swing.ListCellRenderer {
public ColorRenderer() {
this.setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object key, int index,
boolean isSelected, boolean cellHasFocus) {

Color color = colors.get(key);;
String name = key.toString();

list.setSelectionBackground(null);
list.setSelectionForeground(null);

if(isSelected){
setBorder(BorderFactory.createEtchedBorder());
} else {
setBorder(null);
}
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
setBackground(color);
setText(name);
setForeground(Color.black);
if(name.equals("BLACK") || name.equals("DARK_GRAY")){
setForeground(Color.white);
}

return this;
}
}
}

Demo Application:
The below code creates a JFrame by adding JColorComboBox to it.

 

/**
*
* @author sharath
*/
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.*;
public class StartGUIApp {
public static void main(String[] args)throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame.setDefaultLookAndFeelDecorated(true);

JPanel panel = new JPanel();
JLabel label = new JLabel("Select Color");
JColorComboBox box = new JColorComboBox();
panel.add(box);
panel.add(label);
panel.setLayout(null);
label.setBounds(20,20,60,30);
box.setBounds(100,20,140,30);
panel.setSize(250, 100);

JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setSize(panel.getWidth(), panel.getHeight());
setFrameProperties(frame);
}
static private void setFrameProperties(JFrame frame) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Saturday 16 July 2011

Romain guy's blog

If you are interested in designing GUIs and building custom components with Swing toolkit, definitely Romain guy's blog can be good reference for you, he writes about his work on swing components, custom components, tips and tricks on designing and using components. and you can download the demos of his work.


You find more swing articles in 2005, 2006 archives.
His URL: http://www.curious-creature.org/

Saturday 9 July 2011

DesignGridLayout: Simple, yet powerful Layoutmanager for arranging swing components

Swing toolkit comes with few standard Layout Managers where none of them serves the need of arranging components in a way that usually developers require. some of them does, but it takes lot of coding time to achieve it. GridBagLayout is the most flexible layout manager available in swing toolkit but their are so many variables that developer has to look after.

DesignGridLayout can be a useful LayoutManager to arrange components in less time with very small snippet of code and can still get proper alignment. Layouting with DesignGridLayout is as easy as coding with various GUI Builder tools available in varoius IDEs.

Simple program which demonstrates DesignGridLayout:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.java.dev.designgridlayout.DesignGridLayout;
import net.java.dev.designgridlayout.Tag;

public class DesignGridLayoutDemo extends JPanel{

  public DesignGridLayoutDemo () {

      DesignGridLayout layout = new DesignGridLayout(this);
      layout.row().grid().add(new JLabel("Username: ")).add(new JTextField("Enter user name "), 2);

      layout.row().grid().add(new JLabel("Password: ")).add(new JTextField("Enter password "), 2);
      layout.emptyRow();layout.emptyRow();
      layout.row().center().fill().add(new JSeparator());
      layout.emptyRow();layout.emptyRow();
      layout.row().bar().add(new JButton(" Login "), Tag.OK).add(new JButton("Cancel"), Tag.CANCEL);
  }


public static void main(String[] args) throws ClassNotFoundException,
                                InstantiationException,
                                IllegalAccessException,
                                UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
     SwingUtilities.invokeLater(new Runnable() {

         @Override
    public void run() {
          JFrame frame = new JFrame("Login Form");
          frame.getContentPane().add(new DesignGridLayoutDemo ());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          frame.pack();
          frame.setVisible(true);
         }
     });
  }
}
Output:
                                                            
This project has been hosted in java.net site where we can find Tutorial, download links and feature etc.

Monday 4 July 2011

Java IDE for Learners:


           Simple editors like Notepad, Gedit, edit+  definitely allows us to write a program, but it is always difficult to code, debug and manage even smaller applications. and profession IDEs like Eclipse, Netbeans JDeveloper are definitely not suitable for beginners.[They are pretty advanced to students]

           What if we have an IDE which allows the learners to understand the basic coding principles of java, Fundamentals of Object Oriented Programming[OOP] with the pictorial representation along with syntax highlighting, scope highlighting and other cool features?.. sounds good right.
         
                   
           BlueJ is a simple Java based IDE developed by Kent university for the beginners and students of Java programming language. The coolest thing about BlueJ is it not only allows us to interact[compile, execute] with complete application or program but also single objects.Hence we can create Objects and execute its methods graphically.

Important features are:
  • Create classes and interfaces through wizards and diagrams
  • Create directly object of a class and execute its methods rather than executing complete application.
  • Debugger, Terminal etc
Editor Features:
  •      Syntax Highlighting
  •      Scope Highlighting
  •      Code completion
  •      Navigation View
  •      Switch between source code and Documentation 




Sunday 3 July 2011

Controlling an executable from Java program


Windows tools like Notepad, internet explorer and other executable files can be started from java program through its core API.


Procedure to start a Notepad application from java program:

 Create an object for Runtime class
                         Runtime runtime = Runtime.getRuntime();
       
Create the command string
                         String command = "notepad.exe";        
Call exec()
                         try{
                             Process process = runtime.exec(command);
                         }catch(IOException e){
                     
                         }
         For starting Notepad application does not require Process object, but few executables requires I/O operation. In that case we will have to use the process object exclusively.

Simple program which starts Notepad:


                                                                         Fig-1.01


Procedure to start Browser in java Program:

We have seen starting a notepad application from java program, now let us start Internet Explorer with some URL.

The command string varies depending upon the OS and  Browser we are using.

1. Identify current Operating System and Browser:
                                               
        public boolean isWindowsPlatform() {
     
          String OS = System.getProperty("os.name");
          if(OS != null && OS.startsWith(WIN_ID)) {
              return true;
          }else{
              return false;
          }
    }

2. Create FLAG and PATH:
     
        Windows OS:
               Flag is used to display the URL:
                         String WIN_FLAG = "url.dll,FileProtocolHandler";
               Path is used to open the default browser:
                         String WIN_PATH = "rundll32"
                URL:
                          http://www.java.com
         Unix OS:
               Flag to display the URL:
                        String UNIX_FLAG = "-remote openURL";
               To open Netscape Navigator:
                        String UNIX_PATH = "netscape"
               URL:
                         http://www.java-gui.blogspot.com
3. Create Command String:
     
         String command = WIN_PATH+" "+WIN_FLAG+" "+URL; [windows platform]

4.  Create Runtime object and execute the command:
        Runtime runtime = Runtime.getRuntime();
          try {
                 runtime.exec(command);
          } catch(Exception e){
              e.printStackTrace();
          }

Complete program to start Browser:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class StartBrowser {

    public StartBrowser(String URL) {

       String command = null;
        // check OS
       if(isWindowsPlatform()) {

         // create command string
         command = WIN_PATH+" "+WIN_FLAG+" "+URL;
         //pass command to the exec()
         Runtime runtime = Runtime.getRuntime();
         try {
              runtime.exec(command);
         } catch(Exception e){e.printStackTrace();}
       }
    }

    public boolean isWindowsPlatform() {
        String OS = System.getProperty("os.name");
        if(OS != null && OS.startsWith(WIN_ID)) {
            return true;
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
         new StartBrowser("http://www.java-gui.blogspot.com");
    }

    private static final String WIN_ID = "Windows";
    // default browser start from windows.
    private static final String WIN_PATH = "rundll32";
    // The flag to display a url.
    private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
}

Saturday 2 July 2011

Introducing Java 7: Moving Java Forward

Hey check out this!.....Oracle is going to introduce Java 7 on July 7


Some of the latest innovations and changes in Java 7 are:

1. A fully functional and supported NIO.2 filesystem provider for zip and jar files.
2. Small language changes and enhancements [Project Coin]
        Project Coin includes
              Strings in switch statements
              try-with-resource statements
              Improved type inference for generic instance creation
              simplified varargs method invocation
              better integral literals,
              and improved exception handling[multiple catch]
3. Support for Dynamically typed languages

For attending live webcast just by sitting at your desk and for registrations  click below link

To know features and other details



Popular posts

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...