Sie sind auf Seite 1von 14

This program shows you 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 the JFrame 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. Here is the code of the program : import javax.swing.*; public class Swing_Create_Frame{ public static void main(String[] args){ JFrame frame = new JFrame("Frame in Java Swing"); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 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: 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: * 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. Here is the code of the program: 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,"Roseindia.net"); } } } This section show you 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: Image 1 If you click on the second button then the confirm dialog box will open which asks for "Ok" and "Cancel". Image 2 If you click on the "Ok" button then a message dialog box will open with message "You clicked on "Ok" button" like this

Image 4 otherwise message dialog box will open with text "You clicked on "Cancel" button like this Image 6 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: * 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. Here is the code of the program: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ShowMessageDialog{ JButton button; public static void main(String[] args){ ShowMessageDialog md = new ShowMessageDialog(); } public ShowMessageDialog(){ JFrame frame = new JFrame("Message Dialog Box"); button = new JButton("Show simple message dialog box"); button.addActionListener(new MyAction()); JPanel panel = new JPanel(); panel.add(button); button = new JButton("Show \"Ok/Cancel\" message dialog box"); button.addActionListener(new MyAction()); panel.add(button); button = new JButton("Show \"Yes/No/Cancel\" dialog box"); button.addActionListener(new MyAction()); panel.add(button);

frame.add(panel); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public class MyAction implements ActionListener{ public void actionPerformed(ActionEvent ae){ String str = ae.getActionCommand(); if(str.equals("Show simple message dialog box")){ JOptionPane.showMessageDialog(null, "This is the simple message dialog box.", "Roseindia.net", 1); } else if(str.equals("Show \"Ok/Cancel\" message dialog box")){ if(JOptionPane.showConfirmDialog(null, "This is the \"Ok/Cancel\" message dialog box.", "Roseindia.net", JOptionPane.OK_CANCEL_OPTION) == 0) JOptionPane.showMessageDialog(null, "You clicked on \"Ok\" button", "Roseindia.net", 1); else JOptionPane.showMessageDialog(null, "You clicked on \"Cancel\" button", "Roseindia.net", 1); } else if(str.equals("Show \"Yes/No/Cancel\" dialog box")){ JOptionPane.showConfirmDialog(null, "This is the \"Yes/No/Cancel\" message dialog box."); } } } } This section illustrates you how to change the label of a button in java swing. JButton is the component of javax.swing.*; package. The following program helps you to change the label of the button. In this program, the label of the button is changed from "Click Me" to "Roseindia.net" and vice versa whenever you click on the button as shown below: Before: Button Without change the label. After: Changed label of the button. In this program, addActionListener() method has been added to the button to register the action listener and then if you click on the button, the generated

action event is captured in the actionPerformed(ActionEvent e) method. In the actionPerformed(ActionEvent e){ we check the label of the button. If the label of the button is "Roseindia.net", it will change the button label to "Click Me" otherwise it will change the label to "Roseindia.net". setText(String): Above method sets the label of the button. Here is the code of the program: import javax.swing.*; import java.awt.event.*; public class ChangeButtonLabel{ JButton button; public static void main(String[] args){ ChangeButtonLabel cl = new ChangeButtonLabel(); } public ChangeButtonLabel(){ JFrame frame = new JFrame("Change JButton Lebel"); 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){ String text = (String)e.getActionCommand(); if (text.equals("Click Me")){ button.setText("Roseindia.net"); } else{ button.setText("Click Me"); } } } } This section shows you how to set the multi line label on the button in Java Swing Applications. This program uses html class from javax.swing.text.html*; package and then breaks the text label of the button into two lines. If you run the program it will look

like following image: Multiline Labe of the Button HTML: This is the class from the javax.swing.text.html.*; package of Java. This class provides the facility to use the html tags in java application for texts. There are <html></html> tag and <br> tag have been used in this program. Tags of html are used with the string which is the label of the button. Here is the code of the program: import javax.swing.*; import javax.swing.text.html.*; import java.awt.*; public class MultilineLabelButton{ public static void main(String[] args){ JFrame frame = new JFrame("Multiline Label for Button"); String lbl = "<html>" + "This label" + "<br>" + "is in two lines" + "</html>"; Panel panel = new Panel(); JButton button = new JButton(lbl); panel.add(button); // frame.add(button); frame.add(panel, BorderLayout.NORTH); frame.setSize(300, 200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } In this section, you will learn how to remove the title bar of a frame or window in java. That means show the frame or window without title bar. The title bar of the frame or window which holds the icon, minimize button, maximize button and close button with the title of the frame. Following is the image of the frame without title bar: Frame Without Title Bar Code Description: setUndecorated(boolean): This is the method of the JFrame class that sets the frame decoration. It takes a boolean typed value either true or false. If you passes the true then the frame will undecorated means the frame will not show the title bar and if you passes the false then the frame will show the title bar.

Here is the code of the program: import javax.swing.*; public class RemoveTitleFrame{ public static void main(String[] args) { JFrame frame = new JFrame("Removing the Title Bar of a Frame"); frame.setUndecorated(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,400); frame.setVisible(true); } } In this section, you will learn how to make a component draggable in java. This program provides the drag and drop feature from one component to another. This program shows a text box and a label on the frame. When you drag the label and drop to the text box then the text of the label is copied to the text box. For the pictorial representation of the application result is given as follows: Drag And Drop Code Description: There are several APIs has been used to make the component draggable in the program. These are explained as follows: TransferHandler: This is the class of the javax.swing.*; package. This is used to transfer the transferable swing component from on the another. Both components should be the swing component. This class is helpful to copy from one component to another via clipboard. setTransferHandler(): This is the method of the TransferHandler class which makes the component able to transfer the specified part of the component in the TransferHandler() as parameter which specifies the the property of the component which has to be dragged and dropped. This program specifies the text of the label to be dragged and drop to the text box using the string "text". MouseListener: This is the interface which receives the different mouse events. Mouse events can be like: pressing or releasing the mouse, click, enter or exit the mouse etc. are handled through the MouseEvent generated by the MouseListener interface. This program uses the instance of the MouseListener.

exportAsDrag(): This is the method of the TransferHandler class which initiates the component to drag and drop from one to another swing component. This method takes three arguments like: JComponent, Active event, and another is the Action which has to be done. Here, the constant property COPY of the TransferHandler class has been used to copy the text from the label to the text box. Here is the code of the program: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingDragDrop{ JTextField txtField; JLabel lbl; public static void main(String[] args){ SwingDragDrop sdd = new SwingDragDrop(); } public SwingDragDrop(){ JFrame frame = new JFrame("Drag Drop Demo"); txtField = new JTextField(20); lbl = new JLabel("This is the text for drag and drop."); lbl.setTransferHandler(new TransferHandler("text")); MouseListener ml = new MouseAdapter(){ public void mousePressed(MouseEvent e){ JComponent jc = (JComponent)e.getSource(); TransferHandler th = jc.getTransferHandler(); th.exportAsDrag(jc, e, TransferHandler.COPY); } }; lbl.addMouseListener(ml); JPanel panel = new JPanel(); panel.add(txtField); frame.add(lbl, BorderLayout.CENTER); frame.add(panel, BorderLayout.NORTH); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); } } In this example we are converting image of any format into jpg format.

Import java.io.* package and class javax.imageio.ImageIO and java.awt.BufferedImage. The package java.io.* is used for input and output operations through data streams, serialization and the file system. Classes ImageReader and ImagrWriter inherit the static methods from the class javax.imageio..ImageIO for reading and writing the images respectively. The class java.awt.BufferedImage extends Image class and implements WritableRenderedImage interface. The class BufferedImage is used to access an image. The methods used in this example are: write(RenderedImage im, String formatName, File output): This method is used to write an image. This method takes three parameters first one is Renderedimage, second is format in which the image is to be converted and last is name of the file on which the image is to be writen. The format name may be gif, jpg, png etc. read(File input) : This is used to read an image. Code Description: This example reads the image name passed at the command prompt for converting the image into the jpg format. In this example we are reading the image from system by using read() method of ImageIO class. We are using write() method for conversion of an image of any format into the jpg format. Here is the code of the program : import java.io.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; public class GIFToJPG { public static void main(String a[]){ 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); BufferedImage image = ImageIO.read(input); System.out.println("Enter the output image name(.jpg):\n"); String imageName1=bf.readLine(); File output = new File(imageName1); ImageIO.write(image, "jpg", output);

System.out.println("Your image has been converted successfully"); }catch(FileNotFoundException e){ System.out.println("Error:"+e.getMessage()); }catch(IOException e) { System.out.println("Error:"+e.getMessage()); } catch(Exception e){ System.out.println(e.getMessage()); } } } Input on DOS Prompts : C:\image>javac GIFToJPG.java C:\image>java GIFToJPG Enter image name rajeshxml2.gif Enter the output image name(.jpg): raju.jpg Your image has been converted successfully Input image:rajeshxml2.gif Output of The Example:raju.jpg This example takes an image from the system and displays it on a frame using ImageIO 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. Here is the code of the program : 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); } }

Input on dos Prompts : C:\image>javac ShowImage.java C:\image>java ShowImage Enter image name rajeshxml2.gif Input image:rajeshxml2.gif Output of The Example: Here, you will learn about adding event i.e. the rollover and click icon to a JButton component of swing in java. Rollover means moving mouse pointer above the icon on the button. This program shows an icon or image on the button if the mouse pointer moves above the Button then your icon or image should be changed. When you click on the button then another image or icon should be shown on the button. This program displays a button on a frame. Button shows different icons like: cut, copy and paste on different events. At first, the button shows the "cut" icon and when the mouse pointer moves above the button then the button shows the "copy" icon and when you click on the button then the "paste" icon is seen. Following are the screenshot of the application: This the "cut" image which occurs by default when the program is rum from the command prompt. Roll Over : Cut Image (By Default) This is the "copy" image which occurs by default when user will rollover the image or button. Roll Over : Copy Image (When the image is rollovered And this is the "paste" image which occurs by default when user clicks on the button. Roll Over : Paste Image (When the image is clicked) Code Description: These events are managed by the program using some APIs or methods as follows: button.setRolloverIcon(Icon icon_name): This is the method of the JButton class which is used to set the icon or image to

a button for display when the mouse pointer rolls over the icon or the button. The icon or image is passed through the method as a parameter. button.setPressIcon(Icon press): This is the method of the JButton class which is used to set the icon or image to a object for displaying when the button is clicked. The icon or image is specified in the method argument as a parameter. Here is the code of program: import javax.swing.*; import java.awt.*; public class RolloverComponent{ public static void main(String[] args) { JFrame frame = new JFrame("Adding a Rollover and Pressed Icon to a JButton Component"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); frame.add(panel,BorderLayout.CENTER); JButton cutbutton = new JButton(new ImageIcon("cut.gif")); panel.add(cutbutton); ImageIcon rollover = new ImageIcon("copy.gif"); cutbutton.setRolloverIcon(rollover); ImageIcon press = new ImageIcon("paste.gif"); cutbutton.setPressedIcon(press); frame.setSize(400,400); frame.setVisible(true); } }

Das könnte Ihnen auch gefallen