How to do a dropdownlist in java Swing much like a JMenuBar items

Hi sir,
Here i want to know how to do a dropdownlist in java swing much like a JMenuBar items falling from the top to bottom .Here i should not use JMenuBar in any way.
So that i need to do the dropdownlist by using other feature only.Since i am new to this.I need ur help urgently.Pls do provide the code for this so that i will be so gratefull to u.It is very Urgent.Since i have involved in a project which involves this feature.Pls. do provide the answer as well as the code quickly as possible.
Thanx
m.ananthu

use JComboBox
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html

Similar Messages

  • How to use a DropDownList in Java Swing.Its very very Urgent

    Hi Sir,
    Here i need to know how to do (or) create a dropdownlist by using Java Swing.I know that there is JMenuBar & JMenuItems without using that when i click a JButton for example the dropdownlist should come from the top to bottom.I have already posted this quesion once.And i found that it has been removed.So i hope that this time i will get a better answer.Pls.do provide the code as well sir.So that i will be very thankful to u.Since i am involved in a project which contains this
    feature.It is very very Urgent.So pls.do provide the code i will be waiting for the reply.
    Thanx,
    m.ananthu

    use JComboBox
    JComboBox liste = new JComboBox(new Object[]{"azerty","qwerty});the api documentation :
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html
    the turotial on combobox :
    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html

  • How To Call HTML Page Through Java Swing Page  ???....

    Hi All ;
    Please Can You Tell Me How To Call HTML Page Through Java Swing Page ....
    Regards ;

    Hi,
    you can use HTML fragments on a panel.
    http://java.sun.com/docs/books/tutorial/uiswing/components/html.html
    However, to integrate a browser you need 3rd party software like IceBrowser
    If you Google for: HTML Swing
    then you find many more hints
    Frank

  • How to connect autocad file to java swing

    hi,
    plz immediately tell me how to connect autocad file to java swing .
    plz help me
    it is very urgent

    Hi there
    See if the link below helps you out.
    Click here to view
    Cheers... Rick
    Helpful and Handy Links
    Captivate Wish Form/Bug Reporting Form
    Adobe Certified Captivate Training
    SorcerStone Blog
    Captivate eBooks

  • How to print a JTable  in Java Swing ?

    Hi,
    I have an application written in java swing.Now I want to write a print module that prints some details.The details includes the JTextArea and JTable that changes in size dynamically.One solution i found is to put them in a panel and print that panel.But it is static.The size of JTable and JTextArea changes, according to the given input.Please give me a solution for this.

    Printing is a bit of a nightmare, actually. Most of the trouble is layout. Basically a Printable is passed a page number and a graphics context and has to work out what components go on that page and where. It can't depend on the pages being requested in sequence.
    You can call getPrintable from a JTable, and you can call that through your own Printable in order to add extra pages. However you can't ask a Printable how many pages it's going to produce, you just have to invoke it and see if it returns a code to say that the page is out of range.
    And the Printable JTable generates is very limited, the table has to occupy full pages, you can't tell it to start in a different place on the first page, or find out how much space it's used on the last page. The headers and footers generate JTable's own idea of a page number, not yours.
    You can call print() on most Swing components, but you'll need to set their size and location first, and/or mess with the transformation in the graphics context.

  • How to play flash files in java swings

    Hi All ,
    I have a requirement in java swings , i want to play advertisements ( flash files in swings )
    can any one provide any example for the above requirement .
    Thank you all for sharing knowledge in this great forum .
    Jerry

    I have a java desktop application which is actually a
    kiosk application. I have to run some promotion
    videos in my application when no user is using the
    kiosk.Will the kiosks all be running the same OS?
    The reason I ask is that JMF is available in both
    standard and performance pack versions. The PP
    provides a wider variety of formats, but runs only
    on Win. and *nix.
    videos can be any avi or neother which can easily be
    played in java applications.That is handy. The JMF standard pack provides
    support for a number of flavors of AVI, but not all.
    What is the best way for me to play video files in a
    java application??I would suggest checking if the 'standard' version
    of the JMF can play* the current AVI's. If it can, use
    the standard JMF for the project, if not, look to
    converting the AVI's to something the JMF can
    deal with, this might involve storing the video or
    audio of the AVI's in a different format - you
    might have to experiment to get the right
    combination, but the JMF 'supported formats'
    is a good guide.
    http://java.sun.com/products/java-media/jmf/2.1.1/formats.html
    * To check if JMF can play them, install it and
    try loading the AVI's in JMStudio - the default
    player.

  • How to invoke a JAR from Java Swing application?

    Hi,
    I am trying to start a jar file from the swings application.
    I am trying the following code,
    String cmd[] = new String[]{"cmd", "java -jar TestJFreeChart.jar"};
    try
           Process run = Runtime.getRuntime().exec(cmd);
    catch(Exception e)
    {}Is anything wrong in the usage?

    First try:
    "cmd /c java -jar app.jar" or cmd start, because it can't jsut run java.exe, it needs to be
    passed to the cmd interpretor witch further calls java.exe, etc
    Also read what stevejluke suggested. Its important to know if .waitFor or not.
    You wont understand these until you read the tutorial.

  • How to create cascading dropdownlist in java

    hi,
    i am new to java ,i have a employee table that has feilds id,name state city and area. now i have to access employee name based on state city area .i have written console program that displays employee info based on id .now i want a way to acess name by state city and area.ie my program should ask state when i provide state it should display all cities in that state ,then when i select city it should display all area in that city then when i select area it should display all emp name from that area
    import java.util.ArrayList;
    import java.io.*;
    public class Employeelookup {
    static ArrayList<Employeelookup> al = new ArrayList<Employeelookup>();
    int id;
    String name;
    String State;
    String city;
    String Area;
    static int count = 0;
    Employeelookup()
    Employeelookup(int id, String name, String State,String city,String Area)
    this.id = id;
    this.name = name;
    this.State=State;
    this.city=city;
    this.Area=Area;
    count++;
    public void SetId(int id)
         this.id=id;
    public int getId()
         return id;
    public void SetName()
         this.name=name;
    public void putDetails(Employeelookup e)
    al.add(e);
    public Employeelookup getDetails(int id)
    Employeelookup es = (Employeelookup)al.get(id);
    return es;
    public static void main(String[] args ) throws IOException
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    Employeelookup e = new Employeelookup();
    Employeelookup e1 = new Employeelookup(1, "SaiRam", "karnataka","bangalore","rajajinagar");
    Employeelookup e2 = new Employeelookup(2, "Anu", "karnataka","mysore","temple road");
    Employeelookup e3 = new Employeelookup(3, "Vasu", "karnataka","bangalore","rajajinagar");
    Employeelookup e4 = new Employeelookup(4, "Shillu", "Tamil Nadu","madhurai","b");
    Employeelookup e5 = new Employeelookup(5, "Madhu", "Karnataka","shimoga","bus stop");
    Employeelookup e6 = new Employeelookup(6, "Volga", "Andra","abc","railway stop");
    e.putDetails(e1);     
    e.putDetails(e2);
    e.putDetails(e3);
    e.putDetails(e4);
    e.putDetails(e5);
    e.putDetails(e6);
    System.out.println("The total number of Employeelookups are: " +count);
    System.out.println(" ");
    while(true)
    System.out.println("Enter Employeelookup id to get the Employeelookup details: ");
    int id = Integer.parseInt(br.readLine());
    boolean flag = false;
    for(int i=0; i <al.size();i++)     {
    Employeelookup es = e1.getDetails(i);
    if(id == es.id)
    System.out.println("The details of the Employeelookup with id " id " is: ");
    System.out.print(es.id +" " es.name" " es.State" " + es.city+" " es.Area" "+"" );
    flag = true;
    break;
    System.out.println(" ");
    if(!flag)
    System.out.println("Sorry, no data exists with the id " +id);
    System.out.println(" ");
    String ch = null;
    while(true)
    System.out.println("Want to Continue(y/n)?)");
    System.out.println(" ");
    ch = br.readLine();
    if(ch.equalsIgnoreCase("y") || ch.equalsIgnoreCase("n")) break;
    if(!(ch.equalsIgnoreCase("y") || ch.equalsIgnoreCase("n")))
    System.out.println("Invalid option : please type y/n");
    System.out.println(" ");
    if(ch.equalsIgnoreCase("n"))
    System.out.println(" ");
    System.out.println("Thank you");
    break;
    Edited by: 972831 on Nov 22, 2012 10:50 PM

    972831 wrote:
    now i want a way to acess name by state city and area.ie my program should ask state when i provide state it should display all cities in that state ,then when i select city it should display all area in that city then when i select area it should display all emp name from that areaWell, where are you stuck? Take the input and see if it's "state", "city" or "area". Then read another input for its name. Then go through all the items you have and check whether there's a match.

  • How to display XML file in java swing

    hi all
    now i do my M.Sc., project on data maining.this time i have one problem,thats i can't display XML file in swing frame.so any one know this plz give me that idea or code.
    Thanks to all.
    RSK

    One way of doing that is to use JDOM...
    u create an xml tree, and then output using XMLOutputter class...it will be displayed in text...im not sure if thats what u want...however, if u do want to represent it visually then u may need to draw a tree...u may use the Graphics2D for that...there are alot of ways to do such thing, and the 2 possibilities arent the best...depends on what u want...elaborate more pls.

  • How to make .exe file in java swing

    dear friends;
    i am working on a project. I want to create a setup file so that we can install our software any where on the system and for that I have to make .exe file. pls gide me for making .exe file
    thanks and regards
    shashi_vns007

    prigas wrote:
    Make a .jar which is javas equivalent to .exe.Then for the "..setup file.." offer the end user a JWS *(<- link)* based launch that will offer desktop integration (desktop shortcut and menu item) as well as access to automatic updates and much more. JWS will, of course, also work for Mac and Linux OS's.

  • Writing Urdu in java swing component

    Hi firiends,
    I am searching out how to write urdu as input in java swing JTextField. I have searched a lot but still i am unable to get right information. So plz guys help me how i do use urdu on java swing JTextField. i will be higly thankful to you..
    i am waiting your good reponses .
    THANKS
    Sahibzada

    This forum is exclusively for Sun Java Studio Creator. Please post your queries on appropriate forums to have better discussions :
    e.g.
    Swing Forum :
    http://forum.java.sun.com/forum.jspa?forumID=57
    Here are some helpful URLs :
    How to Use Text Areas
    http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html
    http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html#contents

  • How  to  save  content of a  whole  swing  page

    Hi everyone ..
    can any of u tell me ,how to save contents of a java swing page in a single file with all components viz . textfield,textarea,JTable,JPanel etc .. with their respective formatting ie.e Font,Color etc ..
    Plz let me know it soon .. its very urgent ..
    Can I save it as Screenshot or Jpeg Image .. or how to go about it .
    Mohit

    Sure: see below!
    WARNING: this code will not compile as is because it uses some other classes from my personal code library (FileUtil & StringUtil). The particular methods of those classes which are used below are trivial methods that anyone can write, which is is why I have not posted them as well. So, to get the code below to compile, you can
    a) write your own versions of these classes or
    b) simply add the necessary methods to this class or
    c) simply comment out their usage (in the case of StringUtil, which is just used for arg checking)
    But if you still want me to post them, then I can post the relevant fragments of those classes.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import bb.io.FileUtil;
    import bb.util.StringUtil;
    * Class which supports taking screen shots of the entire desktop, AWT Components, or Swing JComponents.
    * This functionality is implemented in a series of <code>take</code> methods, each of which returns a BufferedImage.
    * This class also offers convenience <code>write</code> methods for storing BufferedImages to files.
    * <p>
    * The images taken by this class should be the precise images seen on the screen.
    * <b>However, the images written to files may deviate from the originals.</b>
    * One obvious cause is limitations of the chosen file format (especially with lossy formats like jpeg).
    * A subtle issue can occur, however, even when using lossless formats like png:
    * if the file is subsequently opened by another application,
    * that application may rescale the image, which can often cause visible artifacts.
    * <blockquote>
    *     To see this last problem on Windows XP,
    *     call {@link #take()} which returns an image of the entire desktop and write it to a file,
    *     and then open the file with XP's default graphics file viewer ("Windows Picture And Fax Viewer").
    *     This program shrinks the desktop image in order to fit it inside the program's window,
    *     and rescaling artifacts are readily seen, especially if the desktop image has any kind of text in it.
    *     If "Windows Picture And Fax Viewer" instead cropped the image or had a scroll pane, then this should not happen.
    * </blockquote>
    * <p>
    * Acknowledgement: this class was inspired by the program
    * <a href="http://www.discoverteenergy.com/files/ScreenImage.java">ScreenImage</a>.
    * Differences from the above program:
    * <ol>
    *  <li>this class uses {@link BufferedImage#TYPE_INT_ARGB} instead of {@link BufferedImage#TYPE_INT_RGB} in order to preserve alpha</li>
    *  <li>this class's {@link #formatNameDefault default image file format} is PNG instead of JPEG</li>
    *  <li>this class's <code>take</code> methods simply take snapshots and never have the side effect of writing image files</li>
    *  <li>this class added a version of <code>take</code> which can get a snapshot of a region of a Component</li>
    *  <li>
    *          when taking a snapshot of a region of a Component or JComponent,
    *          the Rectangle that specifies the region always has coordinates relative to the origin of the item
    *  </li>
    * </ol>
    * See also:
    * <a href="http://forum.java.sun.com/thread.jspa?forumID=57&threadID=597936">forum discussion #1 on screen shots</a>
    * <a href="http://forum.java.sun.com/thread.jspa?forumID=256&threadID=529933">forum discussion #2 on screen shots</a>
    * <a href="http://forum.java.sun.com/thread.jspa?forumID=57&threadID=622393">forum discussion #3 on screen shots</a>.
    * <p>
    * It might appear that this class is multithread safe
    * because it is immutable (both its immediate state, as well as the deep state of its fields).
    * However, typical Java gui code is not multithread safe, in particular, once a component has been realized
    * it should only be accessed by the event dispatch thread
    * (see <a href="http://java.sun.com/developer/JDCTechTips/2003/tt1208.html#1">Multithreading In Swing</a>
    * and <a href="http://java.sun.com/developer/JDCTechTips/2004/tt0611.html#1">More Multithreading In Swing</a>).
    * So, in order to enforce that requirement, all methods of this class which deal with components
    * require the calling thread to be the event dispatch thread.
    * See the javadocs of each method for its thread requirements.
    * <p>
    * @author bbatman
    public class ScreenShot {
         // -------------------- constants --------------------
         * Defines the image type for the BufferedImages that will create when taking snapshots.
         * The current value is {@link BufferedImage#TYPE_INT_ARGB}, which was chosen because
         * <ol>
         *  <li>the 'A' in its name means that it preserves any alpha in the image (cannot use the "non-A" types)</li>
         *  <li>the "_INT" types are the fastest types (the "BYTE" types are slower)
         * </ol>
         * @see <a href="http://forum.java.sun.com/thread.jspa?threadID=709109&tstart=0">this forum posting</a>
         private static final int imageType = BufferedImage.TYPE_INT_ARGB;
         * Default value for the graphics file format that will be written by this class.
         * The current value is "png" because the PNG format is by far the best lossless format currently available.
         * Furthermore, java cannot write to GIF anyways (only read).
         * <p>
         * @see <a href="http://www.w3.org/TR/PNG/">Portable Network Graphics (PNG) Specification (Second Edition)</a>
         * @see <a href="http://www.w3.org/QA/Tips/png-gif">GIF or PNG</a>
         * @see <a href="http://www.libpng.org/pub/png/">PNG Home Site</a>
         public static final String formatNameDefault = "png";
         // -------------------- take --------------------
         // desktop versions:
         * Takes a screen shot of the entire desktop.
         * <p>
         * Any thread may call this method.
         * <p>
         * @return a BufferedImage representing the entire screen
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take() throws AWTException, SecurityException {
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              Rectangle region = new Rectangle(0, 0, d.width, d.height);
              return take(region);
         * Takes a screen shot of the specified region of the desktop.
         * <p>
         * Any thread may call this method.
         * <p>
         * @param region the Rectangle within the screen that will be captured
         * @return a BufferedImage representing the specified region within the screen
         * @throws IllegalArgumentException if region == null; region's width and height are not greater than zero
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take(Rectangle region) throws IllegalArgumentException, AWTException, SecurityException {
              if (region == null) throw new IllegalArgumentException("region == null");
              return new Robot().createScreenCapture( region );     // altho not currently mentioned in its javadocs, if you look at its source code, the Robot class is synchronized so it must be multithread safe, which is why any thread should be able to call this method
         // AWT Component versions:
         * Takes a screen shot of that part of the desktop whose area is where component lies.
         * Any other gui elements in this area, including ones which may lie on top of component,
         * will be included, since the result always reflects the current desktop view.
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param component AWT Component to take a screen shot of
         * @return a BufferedImage representing component
         * @throws IllegalArgumentException if component == null; component's width and height are not greater than zero
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take(Component component) throws IllegalArgumentException, IllegalStateException, AWTException, SecurityException {
              if (component == null) throw new IllegalArgumentException("component == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              Rectangle region = component.getBounds();
              region.x = 0;     // CRITICAL: this and the next line are what make region relative to component
              region.y = 0;
              return take(component, region);
         * Takes a screen shot of that part of the desktop whose area is the region relative to where component lies.
         * Any other gui elements in this area, including ones which may lie on top of component,
         * will be included, since the result always reflects the current desktop view.
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param component AWT Component to take a screen shot of
         * @param region the Rectangle <i>relative to</i> component that will be captured
         * @return a BufferedImage representing component
         * @throws IllegalArgumentException if component == null; component's width and height are not greater than zero; region == null
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         * @throws AWTException if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
         * @throws SecurityException if createRobot permission is not granted
         public static BufferedImage take(Component component, Rectangle region) throws IllegalArgumentException, IllegalStateException, AWTException, SecurityException {
              if (component == null) throw new IllegalArgumentException("component == null");
              if (region == null) throw new IllegalArgumentException("region == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              Point p = new Point(0, 0);
              SwingUtilities.convertPointToScreen(p, component);
              region.x += p.x;
              region.y += p.y;
              return take(region);
         // Swing JComponent versions:
         * Takes a screen shot of <i>just</i> jcomponent
         * (no other gui elements will be present in the result).
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param jcomponent Swing JComponent to take a screen shot of
         * @return a BufferedImage representing jcomponent
         * @throws IllegalArgumentException if jcomponent == null
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         public static BufferedImage take(JComponent jcomponent) throws IllegalArgumentException, IllegalStateException {
              if (jcomponent == null) throw new IllegalArgumentException("jcomponent == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              Dimension d = jcomponent.getSize();
              Rectangle region = new Rectangle(0, 0, d.width, d.height);
              return take(jcomponent, region);
         * Takes a screen shot of <i>just</i> the specified region of jcomponent
         * (no other gui elements will be present in the result).
         * <p>
         * Only {@link EventQueue}'s {@link EventQueue#isDispatchThread dispatch thread} may call this method.
         * <p>
         * @param jcomponent Swing JComponent to take a screen shot of
         * @param region the Rectangle <i>relative to</i> jcomponent that will be captured
         * @return a BufferedImage representing the region within jcomponent
         * @throws IllegalArgumentException if jcomponent == null; region == null
         * @throws IllegalStateException if calling thread is not EventQueue's dispatch thread
         public static BufferedImage take(JComponent jcomponent, Rectangle region) throws IllegalArgumentException, IllegalStateException {
              if (jcomponent == null) throw new IllegalArgumentException("jcomponent == null");
              if (region == null) throw new IllegalArgumentException("region == null");
              if (!EventQueue.isDispatchThread()) throw new IllegalStateException("calling thread (" + Thread.currentThread().toString() + ") is not EventQueue's dispatch thread");
              boolean opaquenessOriginal = jcomponent.isOpaque();
              Graphics2D g2d = null;
              try {
                   jcomponent.setOpaque( true );
                   BufferedImage image = new BufferedImage(region.width, region.height, imageType);
                   g2d = image.createGraphics();
                   g2d.translate(-region.x, -region.y) ;     // CRITICAL: this and the next line are what make region relative to component
                   g2d.setClip( region );
                   jcomponent.paint( g2d );
                   return image;
              finally {
                   jcomponent.setOpaque( opaquenessOriginal );
                   if (g2d != null) g2d.dispose();
         // -------------------- write --------------------
         * Writes image to a newly created File named fileName.
         * The graphics format will either be the extension found in fileName
         * or else {@link #formatNameDefault} if no extension exists.
         * <p>
         * Any thread may call this method.
         * <p>
         * @param image the BufferedImage to be written
         * @param fileName name of the File that will write image to
         * @throws IllegalArgumentException if image == null; fileName is blank
         * @throws IOException if an I/O problem occurs
         public static void write(BufferedImage image, String fileName) throws IllegalArgumentException, IOException {
              if (image == null) throw new IllegalArgumentException("image == null");
              if (StringUtil.isBlank(fileName)) throw new IllegalArgumentException("fileName is blank");
              File file = new File(fileName);
              String formatName = FileUtil.getExtension(file);
              if (formatName.length() == 0) formatName = formatNameDefault;
              write(image, formatName, file);
         * Writes image to file in the format specified by formatName.
         * <p>
         * Any thread may call this method.
         * <p>
         * @param image the BufferedImage to be written
         * @param formatName the graphics file format (e.g. "pnj", "jpeg", etc);
         * must be in the same set of values supported by the formatName arg of {@link ImageIO#write(RenderedImage, String, File)}
         * @param file the File that will write image to
         * @throws IllegalArgumentException if image == null; type is blank; file == null
         * @throws IOException if an I/O problem occurs
         public static void write(BufferedImage image, String formatName, File file) throws IllegalArgumentException, IOException {
              if (image == null) throw new IllegalArgumentException("image == null");
              if (StringUtil.isBlank(formatName)) throw new IllegalArgumentException("formatName is blank");
              if (file == null) throw new IllegalArgumentException("file == null");
              ImageIO.write(image, formatName, file);
         // -------------------- Test (inner class) --------------------
         * An inner class that consists solely of test code for the parent class.
         * <p>
         * Putting all the test code in this inner class (rather than a <code>main</code> method of the parent class) has the following benefits:
         * <ol>
         *  <li>test code is cleanly separated from working code</li>
         *  <li>any <code>main</code> method in the parent class is now reserved for a true program entry point</li>
         *  <li>test code may be easily excluded from the shipping product by removing all the Test class files (e.g. on Windoze, delete all files that end with <code>$Test.class</code>)</li>
         * </ol>
         * Putting all the test code in this inner class (rather than a shadow external class) has the following benefits:
         * <ol>
         *  <li>non-public members may be accessed</li>
         *  <li>the test code lives very close to (so is easy to find) yet is distinct from the working code</li>
         *  <li>there is no need to set up a test package structure</li>
         * </ol>
         public static class Test {
              public static void main(String[] args) throws Exception {
                   Gui gui = new Gui();
                   EventQueue.invokeLater( gui.getBuilder() );
                   new Timer(1000, gui.getTimerActionListener()).start();
              private static class Gui {
                   private Frame frame;
                   private TextField textField;
                   private JFrame jframe;
                   private JLabel jlabel;
                   private JPanel jpanel;
                   private int count = 0;
                   private Runnable getBuilder() {
                        return new Runnable() {
                             public void run() {
                                  System.out.println("Creating a Frame with AWT widgets inside...");
                                  frame = new Frame("ScreenShot.Test.main Frame");
                                  textField = new TextField();
                                  textField.setText( "Waiting for the screen shot process to automatically start..." );
                                  frame.add(textField);                              
                                  frame.pack();
                                  frame.setLocationRelativeTo(null);     // null will center it in the middle of the screen
                                  frame.setVisible(true);
                                  System.out.println("Creating a JFrame with Swing widgets inside...");
                                  jframe = new JFrame("ScreenShot.Test.main JFrame");
                                  jlabel = new JLabel(
                                       "<html>" +
                                            "To be, or not to be: that is the question:" + "<br>" +
                                            "Whether 'tis nobler in the mind to suffer" + "<br>" +
                                            "The slings and arrows of outrageous fortune," + "<br>" +
                                            "Or to take arms against a sea of troubles," + "<br>" +
                                            "And by opposing end them?" + "<br>" +
                                            "To die: to sleep; No more;" + "<br>" +
                                            "and by a sleep to say we end" + "<br>" +
                                            "The heart-ache and the thousand natural shocks" + "<br>" +
                                            "That flesh is heir to," + "<br>" +
                                            "'tis a consummation Devoutly to be wish'd." + "<br>" +
                                       "</html>"
                                  jpanel = new JPanel();
                                  jpanel.setBorder( BorderFactory.createEmptyBorder(20, 20, 20, 20) );
                                  jpanel.add(jlabel);
                                  jframe.getContentPane().add(jpanel);
                                  jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                  jframe.pack();
                                  Point p = frame.getLocation();
                                  p.translate(0, frame.getSize().height  + 10);
                                  jframe.setLocation(p);
                                  jframe.setVisible(true);
                   private ActionListener getTimerActionListener() {
                        return new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                  try {
                                       switch (count++) {
                                            case 0:
                                                 displayMessage("Taking a screen shot of the entire desktop...");
                                                 ScreenShot.write( ScreenShot.take(), "desktop.png" );
                                                 break;
                                            case 1:
                                                 displayMessage("Taking a screen shot of the central rectangle of the desktop...");
                                                 Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
                                                 Rectangle region = getCenteredRectangle(d);
                                                 ScreenShot.write( ScreenShot.take(region), "desktopCenteredRectangle.png" );
                                                 break;
                                            case 2:
                                                 displayMessage("Taking a screen shot of the TextField...");
                                                 ScreenShot.write( ScreenShot.take(textField), "textField.png" );
                                                 break;
                                            case 3:
                                                 displayMessage("Taking a screen shot of the central rectangle of the TextField...");
                                                 d = textField.getSize();
                                                 region = getCenteredRectangle(d);
                                                 ScreenShot.write( ScreenShot.take(textField, region), "textFieldCenteredRectangle.png" );
                                                 break;
                                            case 4:
                                                 displayMessage("Taking a screen shot of the JLabel...");
                                                 ScreenShot.write( ScreenShot.take(jlabel), "jlabel.png" );
                                                 break;
                                            case 5:
                                                 displayMessage("Taking a screen shot of the central rectangle of the JLabel...");
                                                 d = jpanel.getSize();
                                                 region = getCenteredRectangle(d);
                                                 ScreenShot.write( ScreenShot.take(jpanel, region), "jpanelCenteredRectangle.png" );
                                                 break;
                                            default:
                                                 System.exit(0);
                                                 break;
                                  catch (Throwable t) {
                                       t.printStackTrace(System.err);
                             private void displayMessage(String text) {
                                  System.out.println(text);
                                  textField.setText(text);
                                  frame.pack();
                                  frame.invalidate();
                             private Rectangle getCenteredRectangle(Dimension d) {
                                  int x = d.width / 4;
                                  int y = d.height / 4;
                                  int width = d.width / 2;
                                  int height = d.height / 2;
                                  return new Rectangle(x, y, width, height);
    }

  • How to create the digital clock in java swing application ?

    I want to create the running digital clock in my java swing application. Can someone throw some light on this how to do this ? Or If someone has done it then can someone pl. paste the code ?
    Thanks.

    hi prah_Rich,
    I have created a digital clock you can use. You will most likely have to change some things to use it in another app although that shouldn't be too hard. A least it can give you some ideas on how to create one of your own. There are three classes.One that creates the numbers. a gui class and frame class.
    cheers:)
    Hex45
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.geom.*;
    public class DigitalClock extends Panel{
              BasicStroke stroke = new BasicStroke(4,BasicStroke.CAP_ROUND,
                                               BasicStroke.JOIN_BEVEL);
              String hour1, hour2;
              String minute1, minute2;
              String second1, second2;
              String mill1, mill2, mill3;
              int hr1, hr2;
              int min1, min2;
              int sec1, sec2;
              int mll1, mll2,mll3;       
        public void update(Graphics g){
             paint(g);
         public void paint(Graphics g){
              Graphics2D g2D = (Graphics2D)g;
              DigitalNumber num = new DigitalNumber(10,10,20,Color.cyan,Color.black);     
              GregorianCalendar c = new GregorianCalendar();
              String hour = String.valueOf(c.get(Calendar.HOUR));
              String minute = String.valueOf(c.get(Calendar.MINUTE));
              String second = String.valueOf(c.get(Calendar.SECOND));
              String milliSecond = String.valueOf(c.get(Calendar.MILLISECOND));
              if(hour.length()==2){
                   hour1 = hour.substring(0,1);
                   hour2 = hour.substring(1,2);
              }else{
                   hour1 = "0";
                   hour2 = hour.substring(0,1);
              if(minute.length()==2){
                   minute1 = minute.substring(0,1);
                   minute2 = minute.substring(1,2);
              }else{
                   minute1 = "0";
                   minute2 = minute.substring(0,1);
              if(second.length()==2){
                   second1 = second.substring(0,1);
                   second2 = second.substring(1,2);
              }else{
                   second1 = "0";
                   second2 = second.substring(0,1);
              if(milliSecond.length()==3){
                   mill1 = milliSecond.substring(0,1);
                   mill2 = milliSecond.substring(1,2);
                   mill3 = milliSecond.substring(2,3);
              }else if(milliSecond.length()==2){
                   mill1 = "0";
                   mill2 = milliSecond.substring(0,1);
                   mill3 = milliSecond.substring(1,2);
              }else{
                   mill1 = "0";
                   mill2 = "0";
                   mill3 = milliSecond.substring(0,1);
              hr1  = Integer.parseInt(hour1);     
              hr2  = Integer.parseInt(hour2);
              min1 = Integer.parseInt(minute1);
              min2 = Integer.parseInt(minute2);
              sec1 = Integer.parseInt(second1);
              sec2 = Integer.parseInt(second2);
              mll1 = Integer.parseInt(mill1);
              mll2 = Integer.parseInt(mill2);
              g2D.setStroke(stroke);
              g2D.setPaint(Color.cyan);
              num.setSpacing(true,8);
              num.setSpacing(true,8);
              if(hr1==0&hr2==0){
                   num.drawNumber(1,g2D);
                   num.setLocation(40,10);
                   num.drawNumber(2,g2D);
              else{
                   if(!(hr1 == 0)){     
                        num.drawNumber(hr1,g2D);
                   num.setLocation(40,10);
                   num.drawNumber(hr2,g2D);
              num.setLocation(70,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(100,10);
              num.drawNumber(min1,g2D);
              num.setLocation(130,10);
              num.drawNumber(min2,g2D);
              num.setLocation(160,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(190,10);
              num.drawNumber(sec1,g2D);
              num.setLocation(220,10);
              num.drawNumber(sec2,g2D);
              /*num.setLocation(250,10);
              num.drawNumber(DigitalNumber.DOTS,g2D);
              num.setLocation(280,10);
              num.drawNumber(mll1,g2D);
              num.setLocation(310,10);
              num.drawNumber(mll2,g2D);
              g2D.setPaint(Color.cyan);
              if((c.get(Calendar.AM_PM))==Calendar.AM){               
                   g2D.drawString("AM",260,20);
              }else{
                   g2D.drawString("PM",260,20);
         String dayOfweek = "";     
         switch(c.get(Calendar.DAY_OF_WEEK)){
              case(Calendar.SUNDAY):
                   dayOfweek = "Sunday, ";
                   break;
              case(Calendar.MONDAY):
                   dayOfweek = "Monday, ";
                   break;
              case(Calendar.TUESDAY):
                   dayOfweek = "Tuesday, ";
                   break;
              case(Calendar.WEDNESDAY):
                   dayOfweek = "Wednesday, ";
                   break;
              case(Calendar.THURSDAY):
                   dayOfweek = "Thursday, ";
                   break;
              case(Calendar.FRIDAY):
                   dayOfweek = "Friday, ";
                   break;
              case(Calendar.SATURDAY):
                   dayOfweek = "Saturday, ";
                   break;
         String month = "";     
         switch(c.get(Calendar.MONTH)){
              case(Calendar.JANUARY):
                   month = "January ";
                   break;
              case(Calendar.FEBRUARY):
                   month = "February ";
                   break;
              case(Calendar.MARCH):
                   month = "March ";
                   break;
              case(Calendar.APRIL):
                   month = "April ";
                   break;
              case(Calendar.MAY):
                   month = "May ";
                   break;
              case(Calendar.JUNE):
                   month = "June ";
                   break;
              case(Calendar.JULY):
                   month = "July ";
                   break;
              case(Calendar.AUGUST):
                   month = "August ";
                   break;
              case(Calendar.SEPTEMBER):
                   month = "September ";
                   break;
              case(Calendar.OCTOBER):
                   month = "October ";
                   break;
              case(Calendar.NOVEMBER):
                   month = "November ";
                   break;
              case(Calendar.DECEMBER):
                   month = "December ";
                   break;
         int day = c.get(Calendar.DAY_OF_MONTH);
         int year = c.get(Calendar.YEAR);
         Font font = new Font("serif",Font.PLAIN,24);
         g2D.setFont(font);
         g2D.drawString(dayOfweek+month+day+", "+year,10,80);
         public static void main(String args[]){
              AppFrame aframe = new AppFrame("Digital Clock");
              Container cpane = aframe.getContentPane();
              final DigitalClock dc = new DigitalClock();
              dc.setBackground(Color.black);
              cpane.add(dc,BorderLayout.CENTER);
              aframe.setSize(310,120);
              aframe.setVisible(true);
              class Task extends TimerTask {
                 public void run() {
                      dc.repaint();
              java.util.Timer timer = new java.util.Timer();
             timer.schedule(new Task(),0L,250L);
    class DigitalNumber {
         private float x=0;
         private float y=0;
         private float size=5;
         private int number;
         private Shape s;
         private float space = 0;
         public static final int DOTS = 10;
         private Color on,off;
         DigitalNumber(){          
              this(0f,0f,5f,Color.cyan,Color.black);          
         DigitalNumber(float x,float y, float size,Color on,Color off){
              this.x = x;
              this.y = y;
              this.size = size;
              this.on = on;
              this.off = off;
         public void drawNumber(int number,Graphics2D g){
              int flag = 0;
              switch(number){
                   case(0):          
                        flag = 125;
                        break;
                   case(1):
                        flag = 96;
                        break;
                   case(2):
                        flag = 55;
                        break;
                   case(3):
                        flag = 103;
                        break;
                   case(4):
                        flag = 106;
                        break;
                   case(5):
                        flag = 79;
                        break;
                   case(6):
                        flag = 94;
                        break;
                   case(7):
                        flag = 97;
                        break;
                   case(8):
                        flag = 127;
                        break;
                   case(9):
                        flag = 107;
                        break;
                   case(DOTS):
                        GeneralPath path = new GeneralPath();
                        path.moveTo(x+(size/2),y+(size/2)-1);
                        path.lineTo(x+(size/2),y+(size/2)+1);
                        path.moveTo(x+(size/2),y+(size/2)+size-1);
                        path.lineTo(x+(size/2),y+(size/2)+size+1);
                        g.setPaint(on);
                        g.draw(path);     
                        return;
              //Top          
              if((flag & 1) == 1){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Top = new GeneralPath();
              Top.moveTo(x + space, y);
              Top.lineTo(x + size - space, y);
              g.draw(Top);
              //Middle
              if((flag & 2) == 2){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Middle = new GeneralPath();
              Middle.moveTo(x + space, y + size); 
              Middle.lineTo(x + size - space,y + size);     
              g.draw(Middle);
              //Bottom
              if((flag & 4) == 4){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath Bottom = new GeneralPath();
              Bottom.moveTo(x + space, y + (size * 2));  
              Bottom.lineTo(x + size - space, y + (size * 2));
              g.draw(Bottom);
              //TopLeft
              if((flag & 8) == 8){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath TopLeft = new GeneralPath();     
              TopLeft.moveTo(x, y + space);
              TopLeft.lineTo(x, y + size - space);          
              g.draw(TopLeft);
              //BottomLeft
              if((flag & 16) == 16){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath BottomLeft = new GeneralPath();     
              BottomLeft.moveTo(x, y + size + space);
              BottomLeft.lineTo(x, y + (size * 2) - space);
              g.draw(BottomLeft);
              //TopRight
              if((flag & 32) == 32){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath TopRight = new GeneralPath();     
              TopRight.moveTo(x + size, y + space);
              TopRight.lineTo(x + size, y + size - space);
              g.draw(TopRight);
              //BottomRight
              if((flag & 64) == 64){
                   g.setPaint(on);
              }else{
                   g.setPaint(off);
              GeneralPath BottomRight = new GeneralPath();     
              BottomRight.moveTo(x + size, y + size + space);
              BottomRight.lineTo(x + size, y + (size * 2) - space);
              g.draw(BottomRight);
         public void setSpacing(boolean spacingOn){
              if(spacingOn == false){
                   space = 0;
              else{
                   this.setSpacing(spacingOn,5f);
         public void setSpacing(boolean spacingOn,float gap){
              if(gap<2){
                   gap = 2;
              if(spacingOn == true){
                   space = size/gap;
         public void setLocation(float x,float y){
              this.x = x;
              this.y = y;
         public void setSize(float size){
              this.size = size;
    class AppFrame extends JFrame{
         AppFrame(){
              this("Demo Frame");
         AppFrame(String title){
              super(title);
              setSize(500,500);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • How to store grid points in a file using Java Swing?

    Please someone help me with any suggestions about how to store the grid points in a file using Java Swing

    Actually i have designed a gridlayout in Java Swing and have added some components to it such as buttons or images....My problem is when I click on any of the cell of the grid,the corresponding cell number should be stored in an external file....Do u have any suggestions on how to do it?

  • How to store the datas in a .txt file in to a JTable in Java Swing

    Hi sir,
    Here i want to know how to store the data's of a .txt file
    in to a JTable in java swing.
    Where here the .txt file like for eg,spooler.txt is in the server and from there it will come to my client machine what i have to do is to take that .txt file and store the datas of the .txt file
    in a JTable.This is what i want.So pls. do help and provide the code as well.I will be thankful.Since i am involved in a project which involves this it is Urgent.
    Thanx,
    m.ananthu

    You can't just display data from a text file in a JTable. You have you understand the structure of the data so that you can parse the data and create a table model that can access the data in a row/column format. Here is an example of a simple program that does this:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172

Maybe you are looking for

  • My MacBook Pro will not boot up. I just get a grey screen with a "no entry" symbol and a spinning time icon. Any ideas as to how I can get over this issue?

    Hi, I tried to start my MacBook Pro are 2 weeks and all I get is a grey screen with a grey no entry sign and a spinning timer. I have tried a reboot with shift cmd and v and it seems to be looping and referring to an external device. Only the power i

  • Audio not working in FCP 7 viewer

    I was working on a project on FCP 7 and everything is fine. I stepped away from my computer for a few minutes and now the audio on the viewer doesn't work! The audio on the sequence works fine. But the audio from a clip on the viewer isn't working. C

  • SQL function column in drop down list's data provider's query

    Just wondering, if it is somehow possible to use SQL function column for drop down list through data provider. At the moment, I am using id column as return value and name as display value from this query through CachedRowSetDataProvider: SELECT ALL

  • Special Button

    Hi all, I need to develop a transaction, a special button is needed to add under the OK button and above the applicaction toolbar,(not on the application toolbar), you can see it in T-Code ES32. It is for create attachment and workflow ... Does anyon

  • How can I use a vector?

    String[] sFile = new String [5]; sFile[0]="access_log"; sFile[1]="access_log.1"; sFile[2]="access_log.2"; sFile[3]="access_log.3"; sFile[4]="access_log.4"; how can I put this strings in the vector?