Вы находитесь на странице: 1из 37

Java Swing What is Java Swing?

The Java Swing provides the multiple platform independent APIs interfaces for interacting between the users and GUIs components. All Java Swing classes imports form the import javax.swing.*; package. Java provides an interactive features for design the GUIs toolkit or components like: labels, buttons, text boxes, checkboxes, combo boxes, panels and sliders etc. All AWT flexible components can be handled by the Java Swing. The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window. Here the following APIs interfaces and classes are available: The following interfaces and it's descriptions to be used by the Java swing.

Descriptions This interface performed the action with the ActionListenerwhere the multiple controls are used for same purposes. This interface defines the data model of components like: BoundedRangeModel sliders and progressBars. It defines the state model for the buttons like: radio ButtonModel buttons, check boxes etc. This interface used by the developer for creating the new CellEditor editor and it has the new components implement interfaces. TheCellEditor implements the wrapper based approach. In this interface, the editor component used ComboBoxEditor to JComboBoxcomponents. This interface represents the data model in a list model ComboBoxModel with the selected items. This interface has JDesktopPane object. DesktopManager The JInternalFrameimplements in the JDesktopPane with the help of DesktopManager. This interface used to graphical representation of the Icon components. It has fixed size picture. JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the combo box data model. This interface used for paint the cell in the list with the help ListCellRenderer of "rubber stamps" . Action

Interfaces

ListModel ListSelectionModel MenuElement MutableComboBoxModel Renderer RootPaneContainer

Scrollable ScrollPaneConstants SingleSelectionModel SwingConstants UIDefaults.ActiveValue UIDefaults.LazyValue

WindowConstants

This interface used for JList components method. It gets the value of each cell of list. This interface indicates the components, which are stable or not. This interface used where the any components are implements in the menu. This interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel. It defines the requirements of an object for displaying the values. This interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc. This interface provides the scrolling to show the large amount of data with the help of JScrollPane. This interface used for JScrollPane components. This interface used to select the one index in a model. You can set the components on the screen to own requirements. It constructs the DefaultListCellRenderer. This enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it using LazyValue.createValue() method. This interface has two methods setDefaultCloseOperation and getDefaultCloseOperation and provides the window close opration.

The following classes and it's descriptions to be used by the Java swing.

Classes AbstractAction AbstractButton AbstractCellEditor AbstractListModel ActionMap BorderFactory Box

Descriptions This class handles the any types of action and provides JFC Action interface. This class defines the nature of buttons and menu items. It provides a list and contents of the data model. This class defines the data model which provides the list with its contents. This class works with InputMap and performs any action when the key is pressed. This class extends from Object and creates the Border instance in the factory. It provides the fixed spaces between two components and uses the BoxLayout object of the layout manager.

This class participates in the Layout and uses the lightweight components. This class uses the arranging the multiple components BoxLayout either horizontally or vertically. The Box container uses this class. This class used to create the multiple buttons in ButtonGroup aButtonGroup object. This class used to insert the components like: JList, CellRandererPane JTable and JTree. This class has ComponentInputMap constructor and ComponentInputMap creates the components with the help of InpuMap. It extends from the Graphics and used to debug the DebugGraphics graphics This class provides the implementation of default DefaultBoundedRangeModel BoundedRangeModel. DefaultButtonModel This class implements the generic ButtonModel. It implements the TableCellEditor and TreeCellEditor DefaultCellEditor for the table and tree cells. DefaultComboBoxModel It provides the default model for combo boxes. It implements the DesktopManager. The DefaultDesktopManager DesktopManager has the JInternalFrame for creating the internal fame in a frame. DefaultFocusManager It provides the implementing the FocusManager. DefaultListCellRanderer It implements the default ListCellRanderer. DefaultListCellRanderer.UIResource This extends the DefaultListCellRanderer and implementing in the UIResource. It extends the AbstractListModel and implementing DefaultListModel thejava.util.Vector. DefaultListSelectionModel This class used for select the list in a data model. DefaultSingleSelectionModel This class provides the default SingleSelectionModel. FocusManager It handles all focus like: gainedFocus and lostFocus. It extends the RGBImageFilter and used for disabling GrayFilter the image through the button. This class implements the Icon and paints the icons from ImageIcon the images. This class uses the ActionMap to performed the action InputMap when you press any key of keyboard. It bounds data between the input event and an object. This class helps you when you works with the text fields InputVerifier through the focus. This class extends the Applet and implements JApplet the Accessibleand RootPaneContainer. This class extends the AbstractButton and you can JButton create the new button. Box.Filler

JCheckBox

JCheckBoxMenuItem JColorChooser JComboBox

JComponent JDesktopPane

JDialog

JEditorPane JFileChooser JFrame JInternalFrame

JInternalFrame.JDesktopIcon JLabel JLayeredPane JList JMenu

JMenuBar JMenuItem JOptionPane

This class extends the JToggleButton and implements the check box in which buttons are selected or deselected. It extends the JMenuItem and determines the items which is selected or deselected. It extends the JComponent and implementing the Accessable. Here, you choose and manipulate the colors. This class extends the JComboBox. It provides the dropdown list where user select only one item or value at a time. But combo box is a combination of multiple text or buttons etc. In java swing, All components are used the JComponent except the top-level containers like: JFrame, JDialog etc. This class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane has DesktopManager. It extends the Dialog. This class used to create the dialog window and when you want to create the custom dialog window with the help of JOptionPane method. This class extends the JTextComponent. It edits the component by the EditorKit. This class provides the facility to choosing the file. It extends the Frame and supports the swing components architecture. This class extends from the JComponent and provides the facility to dragging, closing, resizing and menu bar of the internal frame. The JInternalFrame added into the JDesktopPane. It displays the desktop icon and create the instance of JInternalFrame and iconify. This class used to show the small text and image. It has JFC/Swing container that can be used to overlap the components to each other. This class used to create a list where you select the one or more than objects. This class used to create a new menu where you add the JMenuItems. When you select the item then shows the popup menu items in the JMenuBar. It used to create a new menu bar where the JMenu objects are added. This class used to create new menu items in the mebus. It used to create some different types of dialog box like: message dialog box, error dialog box etc.

It extends the JComponent and used to create a new panel. It provides the single line text editing. Here, don't JPassworkField available the original characters but view type indication characters are available. JPopupMenu This class used to create a popup menu. It provides small window where the various types of choices are available. JPopupMenu.Separator Here the popup menu and the separator are available. It shows the integer types values in percent within a JProgressBar bounded range to determine the working process. It implements the radio button and shows the state of an JRadioButton item selected or deselected. It extends the JMenuItem and implements the radio JRadioButtonMenuItem button menu item This class provides the component behind the scenes by JRootPane JFrame, JWindow, JDialog etc. for providing the taskorientation and functionality. JScrollBar This class used to create a scroll bar. It provides the view content area where you show the content to scroll this. JScrollPane It provides the scrollable view components. JSeparator This class use the separator among the components. This class provides a control to represent a numeric JSlider value by dragging the slider. This class used to divides the two components JSplitPane graphically like: top and button, left and right. This class provides the tab component through which JTabbedPane you can switch from one component to another component regarding to the specific tab button by clicking on that. It provides the user interface component and represents JTable the two dimensional data. It provides the multi line plain text area. JTextArea JTextField It provides the facility to editing the text in a single line. This class provides the component like JTexArea for JTextPane multiple lines text with more capabalities. It implements two state button that means selected or JToggleButton deselected. JToggleButton.ToggleButtonModel It extends the DefaultButtonModel and provides theToggleButton model. It provides set of command buttons icons that performs JToolBar the different actions or controls. JToolBar.Separator It provides the tool bar separator. JToolTip It shows the tool tips related to it's components. JPanel

JTree JTree.DynamicUtilTreeNode JTree.EmptySelectionModel JViewPort JWindow

KeyStroke LayoutFocusTraversalPolicy LookAndFeel

MenuSelectionManager OverlayLayout ProgressMonitor ProgressMonitorInputStream

RepaintManager ScrollPaneLayout

ScrollPaneLayout.UIResource SizeRequirements SizeSequence SwingUtilities Timer ToolTipManager UIDefaults UIDefaults.LazyInputMap

UIDefaults.ProxyLazyValue UIManager

It shows the data in a hierarchical way. This extends the DefaultMutableTreeNode and create children nodes. It does not allows the any selection. It gives you about the underlying information. It extends window and shows the any location or area on the desktop. It couldn't any title bar and window management buttons. This class controls the key events on the keyboard for the equivalent device. This class conducts the sorting objects according to their size, type, position or orientation. It provides the dramatically changes in the component like frame related to the graphics for the application. Through this the application can be done very efficient and easier. It has menu selection hierarchy. The layout manager arrange the components. This class is used to monitoring the progress of any operation to be done. This class creates a progress monitor to monitor the progress of reading input from the input stream. It cleanups all the rights when the stream is closed. This class manage and override the repaint requests. It implements the LayoutManager and manage the components like: scroll bar, row header, column header etc. It extends the ScrollPaneLayout and implements theUIResource. It calculates the size and positions of components. It represents the order list of size and it's positions. This class has utilities methods for swing. Actions perform the predefined rate. It manages the all tool tips. It extends the Hashtable and you set/get the value with the help of UIManager. This class creates a Input Map through it's createValue() method. The array of key after binding is passed to the constructor of this. Example of binding of key is array of pressing key information (e.g. ctrl + c or alt + f). This class is used to create a lazy value which is used to delay loading of the class to create instance for that. This class has track of the current look and feel details.

UIManager.LookAndFeelInfo

ViewportLayout

This is the nested class of UIManager class i.e. used for getting information about all the look and feels installed with the software development kit. It implements the LayoutManager and defines the policy for the layout.

The following Exceptions and it's description to be used by the Java swing.

Descriptions This exception occurred when the look and feel classes UnsupportedLookAndFeelException are not supported to user's system.
So Well, Swing is important to develop Java programs with a graphical user interface (GUI). There are many components which are used for the building of GUI in Swing. The Swing Toolkit consists of many components for the building of GUI. These components are also helpful in providing interactivity to Java applications. Following are components which are included in Swing toolkit:
y y y y y

Exception

list controls buttons labels tree controls table controls

All AWT flexible components can be handled by the Java Swing. Swing toolkit contains far more components than the simple component toolkit. It is unique to any other toolkit in the way that it supportsintegrated internationalization, a highly customizable text package, rich undo support etc. Not only this you can also create your own look and feel using Swing other than the ones that are supported by it. The customized look and feel can be created using Synth which is specially designed. Not to forget that Swing also contains the basic user interface such as customizable painting, event handling, drag and drop etc. The Java Foundation Classes (JFC) which supports many more features important to a GUI programcomprises of Swing as well. The features which are supported by Java Foundation Classes (JFC) arethe ability to create a program that can work in different languages, the ability to add rich graphics functionality etc.

The features which are provided by Swing and the Java Foundation Classes are as follows: Swing GUI Components There are several components contained in Swing toolkit such as check boxes, buttons, tables, text etc. Some very simple components also provide sophisticated functionality. For instance, text fieldsprovide formatted text input or password field behavior. Furthermore, the file browsers and dialogs can be used according to one's need and can even be customized.

Java 2D API
Programming has become more interactive with Java 2D API. You can add images, figures, animation to your GUI and even pass visual information with the help of Java 2D API. You can easily use 2D within Swing components such as drop shadows sinceSwing is built on 2D package. Pluggable Look and Feel The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window. You can create your own look and feel using Synth package. There are many of existing look and feels which are available to Swing programs provided by GTK+ look and feel.Moreover, the look and feel of the platform can be specified by the program while running and also to use Java look and feel can be specified by it. The pluggable look and feel indicates that the whole look of the GUI element can be changed i.e. both the visual representation and behavior of a GUI can be changed at the time of display of the component. The new object which is created by the Swing application i.e. a new button by instantiating the JButton class already knows that how to react to mouse movements and mouse clicks. Some tasks are only performed by certain specialized classes like mouse handling that is why there is no need to change the code to modify the look. However, if the code is contained by the button itself that creates its visual representation then this code would be required to be changed to modify the look and feel of the GUI. Due to this reason only Swing provides custom look and feel. Lets tweak the example below that shows how pluggable look and feel affects programming. import java.awt.*;

import java.awt.event.*; import javax.swing.*; import javax.swing.border.*;

public class SwingDemo extends JFrame{ JLabel msgLabel; public SwingDemo(){ super("Swing"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } });

ActionListener al = new ActionListener(){ public void actionPerformed(ActionEvent ae){ msgLabel.setText(((JButton)ae.getSource()).getText()); } };

JButton button; JPanel buttonPanel = new JPanel(); buttonPanel.setBorder(new TitledBorder("Click a button")); for (int i = 0; i < 3; i++){ button = new JButton("Button " + (i + 1)); button.addActionListener(al); buttonPanel.add(button); } JPanel p = new JPanel(new BorderLayout()); p.setBorder(new EmptyBorder(8, 8, 8, 8)); msgLabel = new JLabel("No button pressed!"); p.add(msgLabel, BorderLayout.NORTH); p.add(buttonPanel, BorderLayout.CENTER); setContentPane(p); pack(); setVisible(true); } public static void main(String[] args){ new SwingDemo(); }}

Data Transfer
Swing supports data transfer through drag and drop, copy-paste, cut-paste etc.Data transfer works between Swing components within an application and between Java and native applications. The ability of data transfer is beneficial to programs between Java applications, between components etc. There are two ways to transfer data. These are: 1. The diagram below displays the Drag and drop (DnD) functionality of Swing.

2. The diagram below displays the cut/copy and paste functionality of Swing. That is the clipboard transfer via cut/copy and paste. The path of the data is shown by the arrows.

To be more precise, first of all the bundling of data takes place into a package known asTransferable to begin Data Transfer. Then the data gets extracted by an object i.e. TransferHandlerfrom the Transferable which is provided by the component.

Internationalization
Swing in Java also supports the feature ofInternationalization. The developers can build applications by which the users can interact worldwide in different languages.They can also create applications that can accept input in languages having different characters such asFrench, Spanish, Japanese, etc. An automatic support is provided by the Swing's layout managers required by the UI. That is Swing's layout manager let the UI to appear from right to left in a locale. Hence to let the UI work for left to right and right to left and also to take care of the size of components that change on localization, you need to code the UI only once. Lets see how to internationalize the program given below. import java.util.*; public class InternationalizationDemo { public static void main(String[] args) { System.out.println("The text displayed is specific to locale"+" ("+Locale.getDefault().getDisplayLanguage() +", "+ Locale.getDefault() .getDisplayCountry () + ").\n"); System.out.println("Hello, how are you?"); System.out.println("Thanks to visit."); } } Now you want this program to get internationalized so that it may response according to the specific region and country i.e. locale (Remember no code changes are required for different locale). Just follow these steps: 1. Create Properties Files: Create ?. properties? file containing a set of key and value pair. Remember to keep the keys same in all the files and provide values according to the locale in different files.

Properties Files Naming Convention: Creating a default properties file is a good practice, which is available to the program by default. You can give any name to this file but remember to use the same name that your ResourceBundle uses (MessageBundle.properties file in our example). While naming other properties files follow the syntax: PropertiesFileNameUsedInResourceBundle_languageCode_countryCode.properties Let?s create these files. Default file: Write down the following lines in a plain-text file (Default version) and save it asMessagesBundle.properties: localeInfo = The text displayed is specific to locale welcome = Hello, how are you? sayThanks = Thanks to visit. Other properties files: Write down the following lines in a plain-text file (for the French version) and save it asMessagesBundle_fr_FR.properties: localeInfo = Le texte affich est spcifique la scne welcome = Bonjour, comment allez-vous ? sayThanks = Merci pour visiter. Write down the following lines in a plain-text file (for the Spanish version) and save it asMessagesBundle_es_ES.properties: localeInfo = El texto mostrado es especfico al lugar welcome = Hola, Cmo est usted?. sayThanks = Gracias a visita.

Notice that ?localeInfo?, ?welcome?, ?sayThanks? keys are same in English, French, Spanish files and values are replaced with the converted value of the particular language. 2. Remove hard coded text from the source file: Our next step is to remove the hard coded text from our source file and use the keys of properties file. These values are picked up at the run time from the properties file according to the locale provided to the program. So this source file doesn?t require to be compiled while dealing with the different locales. You can be sure of this fact viewing the code modified below: import java.util.*; public class InternationalizationDemo{ public static void main(String[] args){ String language; String country; Locale locale; ResourceBundle rb; if (args.length != 2){ language = new String("en"); country = new String("US"); } else{ language = new String(args[0]); country = new String(args[1]); }

locale = new Locale(language, country); rb = ResourceBundle.getBundle("MessagesBundle", locale); System.out.println(rb.getString("localeInfo") + "(" + locale.getDisplayLanguage() + "," + locale.getDisplayCountry() + ").\n"); System.out.println(rb.getString("welcome")); System.out.println(rb.getString("sayThanks")); } } When the set of language code and country code is provided at run time, the output is shown according to that particular locale. For example, in the output below, for ?es? and ?ES? the output is displayed inSpanish language. The text displayed is fetched from MessageBundle_es_ES.properties file. If ?fr? and ?FR? codes are provided at run time then values are displayed in French language. Now this text is fetched from MessageBundle_fr_FR.properties file. Here we are not changing and compiling the source code to work for different locale because the program references the keys, not the values. Way to run:C:\Program Files\Java\jdk1.6.0_01\bin>javac InternationalizationDemo.java C:\Program Files\Java\jdk1.6.0_01\bin>java InternationalizationDemo The text displayed is specific to locale (English,United States). Hello, how are you? Thanks to visit. C:\Program Files\Java\jdk1.6.0_01\bin>java InternationalizationDemo fr FR Le texte affich est sp cifique la sc ne (French,France). Bonjour, comment allez-vous ? Merci pour visiter. C:\Program Files\Java\jdk1.6.0_01\bin>java InternationalizationDemo es ES El texto mostrado es espec fico al lugar. (Spanish,Spain).

Hola, Cmo est usted?. Gracias a visita.

Localization
To translate a text in to a particular language is know as Localization. It is a process by which we can change a text to a different language and also we can add somelocale-specific components. Swingsupports localization in the way that when we localize an application to a particular language and run it in that specific locale then Swing pulls up the localized strings from the resource bundle. After this, the component gets resized by the layout manager. The previous example demonstrates how to localize an application. Undo Framework API To perform undo and redo, the developers can use Swing's undo framework. There are number of actions related to undo and redo which are supported by Swing. Moreover, it can easily be used with any other application such as if you want to undo the add and remove elements from a table, you can easily do that. Flexible Deployment Support Swing also supports the Flexible Deployment of the program. For instance, you can create an applet to run your program within a browser window using Java Plug-in. Several browsers are supported by it like Firefox, Internet Explorer etc. Moreover, a program can also be launched from a browser itself withJava Web Start and can also be run outside of browser as a standard desktop application. Integrating with the Desktop Now the Java applications can be integrated seamlessly with the desktop. This has become possible with the introduction of the Desktop API in version 6 of the Java Platform, Standard Edition (Java SE).There are three types of integration which are supported. These are:
y y

The host system's default email client can be launched. Various functionality of applications like edit, print, open can be launched.

The host system's default browser can be launched with a specific Uniform Resource Identifier (URI).

Creating a Frame :how to create a frame in Java Swing Application. The frame in java works like the main window where your components (controls) are added to develop an application. In the Java Swing, top-level windows are represented by theJFrame class. Java supports the look and feel and decoration for the frame. For creating java standalone application you must provide GUI for a user. The most common way of creating a frame is, using single argument constructor of the JFrame class. The argument of the constructor is the title of the window or frame. Other user interface are added by constructing and adding it to the container one by one. The frame initially are not visible and to make it visible the setVisible(true)function is called passing the boolean value true. The close button of the frame by default performs the hide operation for the JFrame. In this example we have changed this behavior to window close operation by setting the setDefaultCloseOperation() to EXIT_ON_CLOSE value. setSize (400, 400): Above method sets the size of the frame or window to width (400) and height (400) pixels. setVisible(true): Above method makes the window visible. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Above code sets the operation of close operation to Exit the application using the System exit method. import javax.swing.*; public class SwingFrame{ public static void main(String[] args) throws Exception{ JFrame frame = new JFrame("Frame in Java Swing"); JLabel lbl = new JLabel("Crezone Technologies");

frame.getContentPane().add(lbl); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}

Setting an Icon for a Frame in Java


how to set an icon for the frame in Java Swing. This program helps us to set the icon (image) on the title bar of the frame. When you open frame or window the icon situated on the title bar is seen on the taskbar also. For this purposes, various methods as follows has been used: frame.setIconImage(Toolkit.getDefaultToolkit().getImage("icon_confused.gif")); Above method sets the icon for the frame or window after getting the image using the Image class method named getImage(). frame.getDefaultToolkit(): This is the method of the Toolkit class which gets the default toolkit. import javax.swing.*; import java.awt.*;

public class SettingIconFrame{ public static void main(String[] args){ JFrame frame = new JFrame("Setting an Icon for a frame"); frame.setIconImage(Toolkit.getDefaultToolkit().getImage("icon_confused.gif"));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,400); frame.setVisible(true); } }

Dialog Box In Swing Application

Show Dialog Box in Java - Swing Dialogs


Message dialog box is used to display informative messages to the user. In this section we will use JOptionPane class to display the message Dialog box. Our program display "Click Me" button on the window and when user clicks on it program displays Message box with "OK" button and message "Roseindia.net". When you run the program following window will be displayed:

When you click on "Click Me" button, following Message is displayed: with dialog boxes.

Program description: JOptionPane Class: In non-swing application we were using System.in class for input or output some text or numeric values but now in the swing application we can use JOptionPane to show the output or show the message. This way of inputting or outputting works very efficiently in the Swing Applications. The window for showing message for input or output makes your application very innovative. JOptionPane class is available in the javax.swing.*; package. This class provide various types of message dialog box as follows:

A simple message dialog box which has only one button i.e. "Ok". This type of message dialog box is used only for showing the appropriate message and user can finish the message dialog box by clicking the "Ok" button. A message dialog box which has two or three buttons. You can set several values for viewing several message dialog box as follows: 1.) "Yes" and "No" 2.) "Yes", "No" and "Cancel" 3.) "Ok", and "Cancel" A input dialog box which contains two buttons "Ok" and "Cancel".

The JOptionPane class has three methods as follows:


y

showMessageDialog(): First is the showMessageDialog() method which is used to display a simple message. showInputDialog(): Second is the showInputDialog() method which is used to display a prompt for inputting. This method returns a String value which is entered by you. showConfirmDialog(): And the last or third method is the showConfirmDialog() which asks the user for confirmation (Yes/No) by displaying message. This method return a numeric value either 0 or 1. If you click on the "Yes" button then the method returns 1 otherwise 0.

How program Works: This program illustrates you how to show a message dialog box when you click on the button. showMessageDialog(): This method is used to show a message dialog box which contains some text messages. This is being used with two arguments in the program where the first argument is the parent object in which the dialog box opens and another is the message which has to be shown. import javax.swing.*; import java.awt.event.*; public class ShowDialogBox{ JFrame frame;

public static void main(String[] args){ ShowDialogBox db = new ShowDialogBox(); } public ShowDialogBox(){ frame = new JFrame("Show Message Dialog"); JButton button = new JButton("Click Me"); button.addActionListener(new MyAction()); frame.add(button); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class MyAction implements ActionListener{ public void actionPerformed(ActionEvent e){ JOptionPane.showMessageDialog(frame,"Crezone Technology"); } } }

Show Message and Confirm Dialog Box Swing Dialogs


how to display several types of message box. There are three types of message dialog box that you can use in your swing applications, example of each type of dialog boxes are provided here. When your run the program, it will display a frame with three buttons. Once you click on the first button then the simple message box will open which holds only "Ok" button as shown below:

If you click on the second button then the confirm dialog box will open which asks for "Ok" and "Cancel".

If you click on the "Ok" button then a message dialog box will open with message "You clicked on "Ok" button" like this

otherwise message dialog box will open with text "You clicked on "Cancel" button like this

If you click on the third button from the main window or frame then a confirm message dialog box will open with three button i.e. the "Yes", "No" and "Cancel" like the following image:

For this purposes two methods have been used:


y

showMessageDialog(): Above method shows a simple message dialog box which holds only one button i.e. "Ok" button. This method takes four arguments in which, first is the parent object name, second is the message as string, third is the title of the message dialog box as string and the last is the type of the message dialog box. showConfirmDialog(): Above method asks from the user by displaying a message dialog box which contains more than one button. Depending on the parameter passed it can be "Ok" and "Cancel" or "Yes", "No" and "Cancel". This method returns the integer value.

Display Image in Java


This example takes an image from the system and displays it on a frame usingImageIO class. User enters the name of the image using the command prompt and then the program displays the same image on the frame. The image is read from the system by using ImageIO.read(File file) method. The methods used in this example are:. drawImage(Image img,int x,int y,ImageObserver observer): This method is used to draw an image. The image is drawn at the top-left corner at (x, y) coordinates in this graphics context's coordinate space setSize(int height , int width): Use this method to set the size of the frame. setVisible(boolean b): Pass the boolean value as true to display the image or Vice-Versa. Here we are passing the boolean value as true to display the image on the frame. getContentPane(): This method gets the content pane in which our GUI component will be added. Code deacription: In this example first we imports the required packages. Then create a class named ShowImage that extends the Panel class. Now declare a variable of BufferedImage class. Constructor ShowImage()

recieves the name of the image passed at the command prompt in the BufferedReader object and reads the image from the system. Use paint() method to draw the image. Create a frame and an object of ShowImage in the main method. Add this object into content pane, set the size of the frame and define the visibility mode as true to display the image on the frame. import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.JFrame; public class ShowImage extends Panel { BufferedImage image; public ShowImage() { try { System.out.println("Enter image name\n"); BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String imageName=bf.readLine(); File input = new File(imageName); image = ImageIO.read(input); } catch (IOException ie) { System.out.println("Error:"+ie.getMessage()); } }

public void paint(Graphics g) { g.drawImage( image, 0, 0, null); }

static public void main(String args[]) throws Exception { JFrame frame = new JFrame("Display image"); Panel panel = new ShowImage(); frame.getContentPane().add(panel); frame.setSize(500, 500); frame.setVisible(true); } }

Animating Images in Java Application


This section shows you how to create an animation with multiple images. You can see how animation has been implemented in the following program or example. The given program implements the animation using more than one images. Image are given below:

In this program, images are displayed one by one from the list of the images. Images are added to the label on the frame or window. This program shows the image one by one after 1000 milliseconds or 1 second. The time delaying is maintained by thread. Code Description: One method has been used to show images on the frame one by one during the 1000 milliseconds. This collection of images makes the application as an animation.

sleep(int time): This is the method of the Thread class which is used to sleep the program for the specified time. The time to sleep is passed through the sleep() method of the Thread class as parameter. import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class SwingAnimation{ Thread th; ImageIcon images; JFrame frame; JLabel lbl; int i = 0; int j;

public static void main(String[] args){ SwingAnimation sa = new SwingAnimation(); }

public SwingAnimation(){ frame = new JFrame("Animation Frame");

th = new Thread(); lbl = new JLabel(); Panel panel = new Panel(); panel.add(lbl); frame.add(panel, BorderLayout.CENTER); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); for(j = 1; j <= 2; j++){ SwingAnimator(); if (j == 2) j = 0; } }

public void SwingAnimator(){ try{ for(i = 1; i <= 5; i++){ images = new ImageIcon("images/img" + i + ".gif"); lbl.setIcon(images);

th.sleep(1000); } } catch(InterruptedException e){} } }

Create a JRadioButton
you will learn how to create a radio button in java swing. Radio Button is like check box. Differences between check box and radio button are as follows: 1. Check Boxes are separated from one to another where Radio Buttons are the differentdifferent button like check box from a same ButtonGroup. 2. You can checks multiple check boxes at once but this can never done in the case of radio button. You can select only one radio button at once from a group of the radio button. 3. You can check or uncheck the check box but you can on check the radio button by clicking it once. Here, you will see the JRadioButton component creation procedure in java with the help of this program. This example provides two radio buttons same ButtonGroup. These radio buttons represent the option for choosing male or female. Following is the image for the result of the given program:

The creation of JRadioButton are completed by the following methods:

ButtonGroup: This is the class of the javax.swing.*; package, which is used to create a group of radio buttons from which you can select only one option from that group of the radio buttons. This is class is used by creating a instance of if using it's constructor. Radio Buttons are added to the specified group using the add(JRadioButton) method of the ButtonGroup class. JRadioButton: This is the class has been used to create a single radio button for the application. setSelected(): This method sets the value of the radio button. This method takes a boolean value either true or false. If you pass true value then the radio button will be selected otherwise the radio button is not selected. import javax.swing.*; import java.awt.*;

public class CreateRadioButton{ public static void main(String[] args) { CreateRadioButton r = new CreateRadioButton(); }

public CreateRadioButton(){ JRadioButton Male,Female; JFrame frame = new JFrame("Creating a JRadioButton Component"); JPanel panel = new JPanel(); ButtonGroup buttonGroup = new ButtonGroup();

Male = new JRadioButton("Male"); buttonGroup.add(Male); panel.add(Male); Female = new JRadioButton("Female"); buttonGroup.add(Female); panel.add(Female); Male.setSelected(true); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,400); frame.setVisible(true); } }

Setting icon on the button in Java


This program sets the icon on the button in Java Swing. Code description: setIcon(Icon): Above method sets the specified Icon on the button. ImagIcon(String image_name): import javax.swing.*; import java.awt.*;

public class IconButton{ public static void main(String[] args){ JFrame frame = new JFrame("Icon on button"); JButton button = new JButton("Roseindia.net"); Icon imgicon = new ImageIcon("icon_confused.gif"); JPanel panel = new JPanel(); button.setIcon(imgicon); panel.add(button); frame.add(panel, BorderLayout.NORTH); frame.setSize(400, 400); frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

Вам также может понравиться