Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Sunday, January 3, 2010

How to Create Button on Frame

In this section, you will learn how to create Button on frame the topic of Java AWT package. In the section, from the generated output of the following program, complete window or frame is created in the ButtonText class that is the main class where the main() method lies. This part of the topic will show a simple command button labeled with the text "Submit" when the program will be executed.

Here, you will learn simply the procedure of creation a command button on the Java Awt Frame. There is a program for the best illustration the topic has been given ahead.

Description of Program

The following program has used simply the Button class for creating a command button on the frame object.

FlowLayout(): This is the constructor of FlowLayout class. This class is used for arranging the component from left to right. Here this is used for creating the object of the class to set the layout by passing the created object from the setLayout() method of the Frame class.

Here is the code of this program:
import java.awt.*;
import java.awt.event.*;

public class ButtonText {
public static void main(String[] args) {
Frame frame=new Frame("Button Frame");
Button button = new Button("Submit");
frame.add(button);
frame.setLayout(new FlowLayout());
frame.setSize(200,100);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}

How to Write an Action Listener

Action listeners are probably the easiest — and most common — event handlers to implement. You implement an action listener to define what should be done when an user performs certain operation.

An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.

To write an Action Listener, follow the steps given below:

1. Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example:

public class MyClass implements ActionListener {

2. Register an instance of the event handler class as a listener on one or more components. For example:

someComponent.addActionListener(instanceOfMyClass);

3. Include code that implements the methods in listener interface. For example:

public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}

In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source), using the addActionListener method. When the user clicks the onscreen button, the button fires an action event. This results in the invocation of the action listener's actionPerformed method (the only method in the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about the event and its source.

Let us write a simple program which displays how many number of times a button is clicked by the user. First, here is the code that sets up the TextField , button and numClicks variable:

public class AL extends Frame implements WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;

In the above example, the event handler class is AL which implements ActionListener.

We would like to handle the button-click event, so we add an action listener to the button b as below:

b = new Button("Click me");
b.addActionListener(this);

In the above code, Button b is a component upon which an instance of event handler class AL is registered.

Now, we want to display the text as to how many number of times a user clicked button. We can do this by writing the code as below:

public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");

Now, when the user clicks the Button b, the button fires an action event which invokes the action listener's actionPerformed method. Each time the user presses the button, numClicks variable is appended and the message is displayed in the text field.

Here is the complete program(AL.java):

import java.awt.*;
import java.awt.event.*;

public class AL extends Frame implements WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;

public static void main(String[] args) {
AL myWindow = new AL("My first window");
myWindow.setSize(350,100);
myWindow.setVisible(true);
}

public AL(String title) {

super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b = new Button("Click me");
add(b);
add(text);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}

public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}

public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}

}


More Examples: Beeper program example is available in this trail's introduction to events, Introduction to Event Listeners. You can find the entire program in Beeper.java. The other example described in that section, MultiListener.java, has two action sources and two action listeners, with one listener listening to both sources and the other listening to just one.

The Action Listener API

The ActionListener Interface

Because ActionListener has only one method, it has no corresponding adapter class.
Method Purpose
actionPerformed(actionEvent) Called just after the user performs an action.

The ActionEvent Class

Method Purpose
String getActionCommand() Returns the string associated with this action. Most objects that can fire action events support a method called setActionCommand that lets you set this string.
int getModifiers() Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the ActionEvent-defined constants SHIFT_MASK, CTRL_MASK, META_MASK, and ALT_MASK to determine which keys were pressed. For example, if the user Shift-selects a menu item, then the following expression is nonzero:

actionEvent.getModifiers() & ActionEvent.SHIFT_MASK


Object getSource()
(in java.util.EventObject) Returns the object that fired the event.

Examples that Use Action Listeners

The following table lists some of the many examples that use action listeners.

Example Where Described Notes
Beeper This section and Introduction to Event Listeners Contains one button with one action listener that beeps when you click the button.
MultiListener Introduction to Event Listeners Registers two different action listeners on one button. Also registers the same action listener on two different buttons.
RadioButtonDemo How to Use Radio Buttons Registers the same action listener on five radio buttons. The listener uses the getActionCommand method to determine which radio button fired the event.
MenuDemo How to Use Menus Shows how to listen for action events on menu items.
TextDemo How to Use Icons Loads an image in an action listener. Because loading an image can take a while, this program uses a SwingWorker to load the image in a background thread.
TableDialogEditDemo How to Use Tables Registers an action listener through a factory method on the OK button of a color chooser dialog.
SliderDemo How to Use Sliders Registers an action listener on a timer that controls an animation loop.

I am new at JAVA. so which IDE is sutable for me ?

Best JAVA IDE :


// HERE A ADSENSE
Integrated Development Environments (IDE) provide benefits to programmers that plain text editors cannot match. IDEs can parse source code as it is typed, giving it a syntactic understanding of the code. This allows advanced features like code generators, auto-completion, refactoring, and debuggers. Here are the best-of-breed Java IDEs.

1.) Eclipse 3.0 :

Price: Free
License: Open Source (CPL)
Summary: Eclipse is a free IDE that has taken the Java industry by storm. Built on a plugin architecture, Eclipse is highly extensible and customizable. Third-party vendors have embraced Eclipse and are increasingly providing Eclipse integration. Eclipse is built on its own SWT GUI library. Eclipse excels at refactoring, J2EE support, and plugin support. The only current weakness of Eclipse is its lack of a Swing or SWT GUI designer.
The eclipse platform provides tool developers with ultimate flexibility and control over their software technology.
Likes:
  • IDE looks amazing, across all systems, and it is quite responsive...great interface overall!
  • anti-aliased text everywhere, even in UI!
  • ability to format to your line wrapping width.
  • refactoring support ascends from heaven!
  • easy to share code between projects
  • ant integration very well done, ant launcher makes managing project tree very easy.
  • content assist is used whereever possible, not just in editor (wizards scrrens).
  • amazing control over the formatting of java source code, which can be saved as a profile.
  • pasting code formats code automatically!
  • editor tabs can be moved around with drag-and-drop.
  • can double-click editor tabs to expand to full workspace view.
  • has both docked views and fast views (most editors only offer one or the other).
  • very powerful control over how the java compiler handles warnings and errors.
  • very small project-specific footprint on directory tree (.project, .classpath).
  • package view has very nice filtering abilities, for what to show/not show (can now filter closed packages, selected working set).
  • code assist in ant resolves location properties and displayes the path in a tooltip!!
  • code assist shows documentation for each option, especially helpful for ant tasks.
  • awesome integrated diff engine and viewer for comparing files and refactoring changes.
  • can rearrange the order of properties and methods in the "outline" view.
  • context aware templates, tab/shift-tab to jump to different insertion points (markers).

Dislikes :
  • editor does not have a split file view!!
  • lacks general syntax highlighting out of the box (property file highlighting added in 3.1).
  • no "soft" line wrapping (only hard wrapping by issuing the format command).
  • doesn't come with native servlet/J2EE aware plugins (you have to configure a plugin, such as lomboz, webtools or myeclipse).
  • must manually create ant scripts, though the code assist support is very well done.
  • cannot create new buffer without creating linked file (annoyance, fixed in 3.1).
  • double clicking on file in package explorer does not close editor if it is currently open (JEdit feature).
2.) Netbeans 3.x (Sun Microsystems):
Price: Free
License: Open Source (CPL)
Summary: Netbeans is a free IDE backed by Sun Microsystems. It is the main competitor of Eclipse. Netbeans is built on a plugin architecture, and it has respectable third-party vendor support. The main advantage of Netbeans over Eclipse is Netbean's excellent GUI designer. It includes syntax highlighting and language support for Java, JSP, XML/XHTML, visual design tools, code generators, ant and CVS support.
(Free) and derivatives like SunJavaStudio? (Commercial) and Compuware OptimalJ? (Commercial).
Likes:
  • very nice code completion engine, never seems too aggressive, very thorough in what it includes, esp jsp.
  • code formatting/reindent task (located in context menu), especially nice for XML/XHTML.
  • creating custom tag libraries was very easy, step by step process straightforward (once I knew where to look).
  • very nice integration with Tomcat, no setup required, direct pages testing, spawns browser, always updates correctly.
  • can specify default request parameters when testing a page.
  • view generated source code for jsp.
  • the whole Tomcat integration module is superb!.
  • nice jsp tag repository support in jsp editor, very easy to add tag libraries to jsp page.
  • HTTP monitor integration very nice, again, part of integration with servlet engine, A++.
  • can move around tabs, I love this (tabs also don't wrap to next line, big plus).
  • validate JSP is very helpful and quite informative...tells you exactly what is missing.
  • javadoc wizard could come in handy, definitely a cool feature, more than just a GUI.
  • method/field navigator as a select box is a nice idea on main UI, don't take up space.
  • can move around all views, group as tabs, etc...easy to customize placements, but doesn't get too complicated like with "workspaces" in eclipse.
  • block indenting/unindenting function, great for XML/XHTML (hardly need it with the code reformatting).
  • very responsive and quick UI.
  • anti-aliased text in editor.
  • very acceptable IDE layout.
  • can right-click file and "Save as template..." which is especially nice for JSP content pages
  • very nice database browser, manipulator, easy to setup.
Dislikes:
  • UI looks crappy (metal), icons suck.
  • no refactoring or refactoring templates (try/catch, rename field, etc...).
  • no JSTL-EL support in syntax highlighting/code completion.
  • cannot wrap arbitrary text in editor.
  • wierd issues with "mounting" core libraries, causes errors and features not to work correctly, such as code completion...the whole "mounting" thing is very strange.
  • new file wizards too minimial.
  • limited control over formatting of java source code (though the defaults won't kill you and it can reformat nicely).
  • Very difficult (for newbies impossible) to add a regular ol' jar file to a project. Every mechanism seems to work against you.
  • Cannot import sources from somewhere else into project, rather you can only mount them where they are...need a copy mechanism.

3.) JBuilder X (Borland) :

Price: $499 (JBuilder 2007)
License: Proprietary
Summary: Jbuilder has long been the top commercial Java IDE. It is an excellent IDE, but it is not built to be open and extensible by third-part vendors. They have a free version but moving up from the free version gets expensive. JBuilder is a complete Java IDE for EJB, Web and Web Services, offering integration with application servers (namely BEA Weblogic), a Struts designer, unit testing, refactoring and support for several source control systems.
Likes :
  • Code template expansions are very helpful, prevents redundant typing (expand with CTRL-J).
  • Can view images in separate tab.
  • Archive builder offers a nice wizard replacement for many ant tasks.
  • Decent built-in database plugin for managing and querying a SQL database.
  • Built-in makefile task for build, clean, rebuild, no need to create ant script.
  • sound effects are a nice touch.
  • JSTL-EL syntax highlighting support.
  • antialiased text editor.
  • can make edit window full screen by double clicking tab.
Dislikes :
  • EXPENSIVE!
  • options in hard to find places.
  • cannot reformat non-java code, such as XML/XHTML.
  • renaming a project is a recipie for disaster, everything gets screwed (most crucially the paths)!
  • recompiling with an active "web run" will sometimes redeploy, sometimes won't redeploy; it's completely random, so you constantly have to restart the weblogic server.
  • refactoring is crap, even renaming a field screws up the code; possible to hose your project in untold ways by renaming things.
  • adding fields to class doesn't allow specification of access (private|protected|public).
  • cannot delete a directory or a package in a project.
  • jsp validation is not very helpful, just tells you on what line an error occurs.
  • wizard for "implement interface" but no wizard for "extend class".
  • when creating new files, you get a different create screen depending on where you selected the option, CONFUSING!!.
  • no syntax highlighting for java properties files, and no editor.
  • many times the error insight will detect an error, but it won't tell you what the error is until you try to compile.
  • multiple projects can not be viewed at once, must repeatedly toggle which project is displayed.

4.) IntelliJ IDEA :

Price: $499
License: Proprietary
Summary : IntelliJ IDEA is a commercial IDE with a loyal following that swear by it. It has excellent J2EE and GUI support. It is extensible via plugins. Its standout feature is the outstanding refactoring support.
It provides a robust combination of enhanced development tools, including: refactoring, J2EE support, Ant, JUnit, and CVS integration. Packaged with an intelligent Java editor, coding assistance and advanced code automation tools, IDEA enables Java programmers to boost their productivity while reducing routine time consuming tasks.
Likes :
  • Superb block editing, the best I have seen, has a distinct "column mode" setting which can be toggled in the context menu.
  • refactoring works flawlessly, has a nice preview, doesn't hose project.
  • Excellent keymapping support, going so far as to support key sequences ala emacs.
  • Interesting support for anywhere editing (automatically places spaces to fill).
  • Once tld is accessible (in classpath), instant tag support in JSP, no need to "assign" it to the IDE.
  • once setup, tomcat integrate is very streamlined, offers a "dump threads" utility for a sudo-reload, JSPs recompile after save.
  • project view is very simple, easy to understand...arranging projects is user-friendly and intuitive.
  • best looking theme next to Eclipse (even on Linux), limited only by java and fonts.
  • anti-aliased text in editor, also in docked tabs.
  • Struts Console plugin offers great Struts config and tld file support.
  • very nice integrated class browser whenever a class is required for input.
  • keymap hints in UI menus update to reflect current keymappings, not just the default set.
  • ant view allows for filtering of targets using a pick list (great for huge build files).
Dislikes :
  • deployment server must be setup separately.
  • No "X" button on editor tabs to close a file, must right click or use keymapping.

5. JDeveloper (Oracle) :

Price: Free {$218.90 per named user plus per year For Support}
License: Proprietary
Summary: Oracle JDeveloper is an integrated development environment with end-to-end support for modeling, developing, debugging, optimizing, and deploying Java applications and Web services. Oracle JDeveloper 10g introduces a new approach to J2EE development with features that enable visual and declarative development. The innovative OAF simplifies J2EE development.
Likes:
  • very nice integration with embedded OC4J container, very easy to execute test page, updates reflected immediately.
  • browser launcher is configurable (good for tabbed browsing and multiple launches).
  • JSP engine and code editor is the best I have seen, super easy to work with, delightful!
  • code insight for EL expressions!
  • auto insert of taglib uri directive when inserting a taglib in JSP page source.
  • several ways to do block indent formatting (highlight block and tab/shift-tab will indent/unindent).
  • very nice forms for creating all aspects of classes.
  • very nice forms for creating classes from *.tld files and keeping the two in-sync/connected.
  • adding taglibs to a project is somewhat intuitive...if you know what to press, it works just fine.
  • message windows informative on build.
  • deployment descriptors have previews so you know what they are going to encapsulate.
  • nice refactoring support.
  • code template support.
  • the timeout on most "auto" aspects can be configured to happen after a time interval, configured with a slider bar...nice concept!
  • Nice import mechanism for sources, very comprehensive wizard
Dislikes:
  • old stuff tends to hang around, constant have issues with "artifacts" of a project, no "make clean".
  • files can get really messed up if you don't remove them properly from disk...learn the order of doing things and stick with it.
  • no clear way to remove a class altogether, if created by accident (I found it, located in file, NOT intuitive).
  • no way to rename a *.tld file once it is created with wizard.
    somewhat slow, not quite as quick as netbeans.
  • several places where a class or interface is required that you have to do manual typing, no integrated class browser.
  • look and feel is descent, some descent icons.
  • cannot maximize a tab to take up the whole window.
  • no way to make textarea anti-aliased text.
  • doesn't remember last openned directory...argh!!

6. SlickEdit :

Price: $284 for a named user license
License: Proprietary
Summary : SlickEdit is an old greybeard in the IDE space. This powerful commercial IDE is a favorite of developers who must switch between several languages. It is a full-featured IDE in dozens of languages, including Java, C++, C#, and HTML. SlickEdit comes as a standalone application or as a plugin for Eclipse.
Likes:
  • SlickEdit is easy to install and configure.
  • large number of supported platforms.
  • As a coding editor SlickEdit has the usual features one would expect from any professional environment - code completion, syntax highlighting and so on.
  • Best feature of SlickEdit is the ability to customise it, to shape the application to fit your own way of working.
  • When creating a new Java class the editor automatically creates the required directories for the specified package—you don't have to specify the package and class names. This feature adds to SlickEdit's productivity.
  • SlickEdit comes with a powerful debugger that you can use to run Java applications in debug mode and step through the code.
  • This tool also provides a very good interface to write and execute JUnit test scripts from within the editor which will be a great help for those who follow TDD-based application development.
  • One cool thing about SlickEdit is that it provides several code templates you can use to add new features to your workspace. You can also add your own templates (much like custom plug-ins in Eclipse).
Dislike:
  • Customizability however, comes with the downside that the application is at first use quite difficult to get into and use.
  • It would be nice if the tool had an option to auto-generate getter and setter methods for the attributes defined in a Java class.

7.) jEdit :

Price: open source
License: Proprietary
Summary : jEdit is a free, mature, and well-designed programmer's code editor that is written in Java and is highly customizable through plugins and options. This editor is sufficiently powerful to be considered a professional strength IDE.
Like:
  • it's a fine example of a Java desktop tool that looks good, is packed full of useful functionality and has snappy response times.
  • Dozens of macros and plug-ins available.
Dislike:
  • In terms of features not comparable to eclipse or visual studio.

8.) JCreater :

Price: Free
License: Proprietary
IDE from Xinox. JCreator has two editions: JCreator Pro (free 30 day trial), JCreator Standard (completely free). Note also that unlike many other Java IDEs, this one is not coded in Java but is written in C++ and optimised for the Windows platform.
Like:
  • a small download compared to some of the better known Java IDEs.
  • There is some automation in terms of wizards for new workspaces, projects, classes and interfaces.
  • The environment features a some level of configurability, with tool bars, key bindings and links to external tools all available.
  • If you develop on Windows and are looking for something that's fast and light-weight then this is one tool that deserves serious consideration.
Dislike :
  • JCreator runs under Windows, there's no Linux or Unix version.
  • Lack of an effective macro or plug-in architecture means that extending with new functionality is not an option.
  • JCreator clearly doesn't have the full range of functionality that the big platforms - Eclipse and NetBeans - have to offer.

9.) IBM WebSphere Studio Site Developer for Java :

Java IDE for Windows and Linux. Expensive but very powerful IDE for servlets, JSP, and other J2EE development. Not limited to use with the WebSphere app server.
10.) WebLogic Workshop :
BEA WebLogic Workshop 8.1 is a very powerful IDE for developing applications on the BEA WebLogic server. Weblogic Workshop runs on Windows 2000, XP, Linux and Solaris, and requires a Weblogic Server. You can download a free version or a Professional version.






AddThis