Doubt in AWT

Hi,
I have a doubt in AWT. We needed a custom title bar for our dialogs. Since we are using JDK 1.3(Actually J2me personal profile 1.0), its not possible to use setUndecorated() method. Hence we made a custom dialog class extending the java.awt.Window class. Now when I add a button to the dialog, the button isn't generating any ActionEvent on pressing the space-bar over the button even though its generating the KeyEvent. The ActionEvent gets generated on clicking the button with the mouse. What could be the issue? This issue doesn't happen if I extend the Dialog class.
With Regards,
Anand

Light weight components: To draw the components the jvm takes the os routine.
Heavy weight components: To draw the components the JVM takes its own routines.
You can check this. If you draw the awt component in one os it gives the different layout in other os. But this is not in the case of swing.This is the main difference . That's why the main components in big project are done in swing.
if in doubt please ask?
javasans

Similar Messages

  • Please help: RMI and Swing/AWT issue

    Hi guys, I've been having a lot of trouble trying to get a GUI application to work with RMI. I'd appreciate any help. Here's the story:
    I wrote a Java application and its GUI using Netbeans. In a nutshell, the application is about performing searches. I am now at the point where I need exterior programs to use my application's search capabilities, thus needing RMI. Such exterior programs are to call methods currently implemented in my application.
    I implemented RMI, and got the client --> server communication working. However, the GUI just breaks. It starts outputting exceptions, gets delayed, doesn't update properly, some parts of it stop working.... basically hysterical behavior.
    Now take a look at this line within my server class:
    Naming.rebind("SearchProgram", mySearchProgram);
    If I take it out, RMI obviously does not work... but the application and its GUI work flawlessly. If I put it in, the RMI calls work, but the GUI's above symptoms occur again. Among the symptoms are null pointer exceptions which all look similar, are related to "AWT-EventQueue-0", and keep ocurring. Here's just snippet of the errors outputted:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalScrollBarUI.getPreferredSize(MetalScrollBarUI.java:102)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.JScrollBar.getMinimumSize(JScrollBar.java:704)
    at javax.swing.ScrollPaneLayout.minimumLayoutSize(ScrollPaneLayout.java:624)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at java.awt.BorderLayout.minimumLayoutSize(BorderLayout.java:634)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at java.awt.BorderLayout.minimumLayoutSize(BorderLayout.java:634)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at javax.swing.BoxLayout.checkRequests(BoxLayout.java:433)
    at javax.swing.BoxLayout.layoutContainer(BoxLayout.java:375)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicMenuItemUI.getPreferredMenuItemSize(BasicMenuItemUI.java:400)
    at javax.swing.plaf.basic.BasicMenuItemUI.getPreferredSize(BasicMenuItemUI.java:310)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.BoxLayout.checkRequests(BoxLayout.java:434)
    at javax.swing.BoxLayout.preferredLayoutSize(BoxLayout.java:251)
    at javax.swing.plaf.basic.DefaultMenuLayout.preferredLayoutSize(DefaultMenuLayout.java:38)
    at java.awt.Container.preferredSize(Container.java:1558)
    at java.awt.Container.getPreferredSize(Container.java:1543)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1617)
    at javax.swing.JRootPane$RootLayout.layoutContainer(JRootPane.java:910)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    There are no complaints about anything within my code, it's all GUI related whenever I make a bind() or rebind() call.
    Again, any help here would be great... cause this one's just beating me.
    Thanks!

    Maybe you want to change that worker thread to
    not do RMI but anything else (dummy data) to see if it really is RMI, I doubt it, I think you are updating some structures that have to do with swing GUI and hence you will hang.
    Just check this out.

  • The final solution to greek characters in AWT applets(????)

    OK. I have searched the whole web and asked whoever I knew. The question was simple: How do I show greek characters in a TextField in an AWT Applet? Some people said that I should change the font properties inside MY jre/lib installation but then I want EVERYONE and not just ME seeing the greek characters! Adding a greek font into the applet's jar was another "solution" but who wants to have an applet of about 2MBs? So I think I have come up to the answer ... ONLY with jre > 1.4.0 somebody could handle greek characters in AWT Applets without trooble! If somebody has managed to show and handle greek characters in a TextField inside an AWT Applet (which I doubt), I would like to know EXACTLY HOW as I am tired of non-working "solutions"! I hope this post saves you from a lot of time searching for the HolyGrail

    I haven't worked with a TextField but I worked with a JTextField. My solution wasn't very straightforward but it did the job.
    I used this solution in order to work with linux, but you must add an if
    statement to check the OS.
    If your problem was how to view Greek characters in a non internation version of
    Java, then as far as I know, you cannot! Also JDK 1.3.1_01 and j2re 1.4.0_01
    use a different way of loading system fonts, so with the latter you cannot use system fonts unless you put them in you java directory.
    (I use linux so don't be surprissed if these work different in windows)
    import java.io.*;
    public class JTextFieldGr extends javax.swing.JTextField {
    public JTextFieldGr() {
    super();
    myInit();
    public JTextFieldGr(String text) {
    super(text);
    myInit();
    public void myInit() {
    addKeyListener(new java.awt.event.KeyListener() {
    public void keyTyped(java.awt.event.KeyEvent evt){
    try{
    String tmp=""+evt.getKeyChar();
    String uk=new String(tmp.getBytes(),"ISO-8859-7");
    evt.setKeyChar(uk.charAt(0));
    }catch(UnsupportedEncodingException e){
    e.printStackTrace();
    public void keyPressed(java.awt.event.KeyEvent evt){
    public void keyReleased(java.awt.event.KeyEvent evt){
    }

  • C++ form with awt controls do not respond

    I have created mfc project in visual studio c++ 6.0. Then I modified MainFrm.cpp.
    Here in CMainFrame::OnShowWindow I initialize jvm, create WEmbeddedFrame and put Button in it. Is runs ok, but 2 problems:
    1. I can't click button. Just as there is some panel over java gui and it catches all mouse and keyboard events.
    2. java gui some times do not repaints itself, or repaints only part of it
    The form was inspired by http://www.codeproject.com/KB/cpp/OOJNIUse.aspx (but I do not use OOJNI, as you can see).
    There is a bug in WEmbeddedFrame, but it deals with swing, not awt: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4982522. To work around it I call addNotify() method.
    Can someone help me with this code?
    // MainFrm.cpp : implementation of the CMainFrame class
    #include "stdafx.h"
    #include "mfc.h"
    #include <jni.h>
    #include <string.h>
    #include <jawt.h>
    #include <jawt_md.h>
    #include <comdef.h>
    #include "MainFrm.h"
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #endif
    // CMainFrame
    IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
    BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
         ON_WM_CREATE()
         ON_WM_SHOWWINDOW()
    END_MESSAGE_MAP()
    static UINT indicators[] =
         ID_SEPARATOR,           // status line indicator
         ID_INDICATOR_CAPS,
         ID_INDICATOR_NUM,
         ID_INDICATOR_SCRL,
    jobject obj_frame;
    JNIEnv *env;
    jclass class_JString;
    // CMainFrame construction/destruction
    CMainFrame::CMainFrame()
         // TODO: add member initialization code here
    CMainFrame::~CMainFrame()
         //jvm->DestroyJavaVM();
          TRACE0("JVM destroyed\n");
    int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
         if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
              return -1;
         if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
              | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
              !m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
              TRACE0("Failed to create toolbar\n");
              return -1;      // fail to create
         if (!m_wndStatusBar.Create(this) ||
              !m_wndStatusBar.SetIndicators(indicators,
                sizeof(indicators)/sizeof(UINT)))
              TRACE0("Failed to create status bar\n");
              return -1;      // fail to create
         // TODO: Delete these three lines if you don't want the toolbar to be dockable
         m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
         EnableDocking(CBRS_ALIGN_ANY);
         DockControlBar(&m_wndToolBar);
         return 0;
    void CMainFrame::OnShowWindow(BOOL bShow, UINT nStatus) {
         CFrameWnd::OnShowWindow(bShow, nStatus);
         //******************************** JAVA
         JavaVM * jvm;
         long status;
          JavaVMOption options[2];
         JavaVMInitArgs vm_args;
          options[0].optionString = ".Djava.class.path=.;c:\\";
          options[1].optionString = "-verbose:jni";
         memset(&vm_args, 0, sizeof(vm_args));
         vm_args.ignoreUnrecognized = true;
          vm_args.version = JNI_VERSION_1_4;
         vm_args.nOptions = 2;
         vm_args.options = options;
          status = JNI_CreateJavaVM(&jvm, (void**) &env, &vm_args);
         if (status == JNI_ERR) {    
              return;
          TRACE0("JVM created\n");
          //class_JString = env->FindClass("foo/Test");
          TRACE0("Class found\n");
          //create frame
          //jmethodID id_Test = env->GetMethodID(class_JString, "<init>", "(J)V");
          TRACE0("Method found\n");
          //obj_frame = env->NewObject(class_JString, id_Test, m_hWnd);
          TRACE0("Object created\n");
         jclass class_Button = env->FindClass("java/awt/Button");
          TRACE0("Class Button found\n");
         jclass class_WEmbeddedFrame = env->FindClass("sun/awt/windows/WEmbeddedFrame");
          TRACE0("Class WEmbeddedFrame found\n");
         jclass class_Container = env->FindClass("java/awt/Container");
          TRACE0("Class Container found\n");
          jmethodID b_const = env->GetMethodID(class_Button, "<init>", "(Ljava/lang/String;)V");
          TRACE0("Constructor Button found\n");
          jmethodID f_const = env->GetMethodID(class_WEmbeddedFrame, "<init>", "(J)V");
          TRACE0("Constructor WEmbeddedFrame found\n");
          jmethodID f_add = env->GetMethodID(class_Container, "add", "(Ljava/awt/Component;)Ljava/awt/Component;");
          TRACE0("Method WEmbeddedFrame.add found\n");
          jmethodID f_setSize = env->GetMethodID(class_WEmbeddedFrame, "setSize", "(II)V");
          TRACE0("Method WEmbeddedFrame.setSize found\n");
          jmethodID f_show = env->GetMethodID(class_WEmbeddedFrame, "show", "()V");
          TRACE0("Method WEmbeddedFrame.show found\n");
          jmethodID f_addNotify = env->GetMethodID(class_WEmbeddedFrame, "addNotify", "()V");
          TRACE0("Method WEmbeddedFrame.addNotify found\n");
          jobject button = env->NewObject(class_Button, b_const, env->NewStringUTF("qqq"));
          TRACE0("Button created\n");
          jobject frame = env->NewObject(class_WEmbeddedFrame, f_const, m_hWnd);
          TRACE0("WEmbeddedFrame created\n");
          env->CallVoidMethod(frame, f_addNotify);
          TRACE0("Frame added Notify\n");
          env->CallVoidMethod(frame, f_setSize, 100, 100);     
          TRACE0("WEmbeddedFrame setSize called\n");
          env->CallVoidMethod(frame, f_add, button);
          TRACE0("Button added\n");
          env->CallVoidMethod(frame, f_show);
          TRACE0("Frame shown\n");
          //******************************** JAVA
          ShowWindow(SW_NORMAL);
    BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
         if( !CFrameWnd::PreCreateWindow(cs) )
              return FALSE;
         // TODO: Modify the Window class or styles here by modifying
         //  the CREATESTRUCT cs
         return TRUE;
    // CMainFrame diagnostics
    #ifdef _DEBUG
    void CMainFrame::AssertValid() const
         CFrameWnd::AssertValid();
    void CMainFrame::Dump(CDumpContext& dc) const
         CFrameWnd::Dump(dc);
    #endif //_DEBUG
    // CMainFrame message handlers

    Don't post new questions on old threads.
    ...in C calling a Java Applet. And your program do it.How do you figure?
    I seriously doubt that the fundamental problem here is a JNI problem versus just a java one. I would expect that the applet viewer either calls a Sun class or even a Java API class. Nothing more. Asking a carefully phrased question in one of the GUI forums might get the answer as well as getting the Sun source for any recent jdk and looking at the code for the applet viewer.

  • Inner Classes doubts

    Hi All,
    I am trying to learn Inner classes in Java. I am referring to the book Core Java by Horstmann and Cornell.
    I know that there are various types of inner classes namely:
    - Nested Inner classes
    - Local Inner classes
    - Annonymous Inner classes
    - static inner classes
    First I am on with Nested Inner classes :
    Following is the code which I am executing :
    package com.example.innerclass;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    public class InnerClassTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TalkingClock clock = new TalkingClock(1000,true);
              clock.start();
    //          JOptionPane.showMessageDialog(null,"Quit Program");
    //          System.exit(0);
    class TalkingClock
         private int interval;
         private boolean beep;
         public TalkingClock(int interval, boolean beep){
              this.interval = interval;
              this.beep = beep;          
         public void start(){
              ActionListener listener = new TimePrinter();
              Timer t = new Timer(interval,listener);
              t.start();
         private class TimePrinter implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   Date now = new Date();
                   System.out.println("At the tone time is : "+now);
                   if(beep)
                        Toolkit.getDefaultToolkit().beep();
    }Following are my doubts :
    1. Why do we need to give the line
    JOptionPane.showMessageDialog(null,"Quit Program");
    System.exit(0);without this line the program doesn't show any output.
    2. I didn't understand this syntax.
    You can write inner object constructor more explicitly using the syntax. :
    outerObject.new InnerClass(construction parameters)
    For e.g.
    ActionListener listener = this.new TimePrinter();
    Here the outer class reference of the newly constructed TimePrinter object is set to this reference of the method that creates the inner class object. the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicilty naming it. For e.g if TimePrinter were a public inner class, you could construct a TimePrinter for any talking clock.
    TalkingClock jabberer = new TalkingClock(1000,true);
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    Please do help me understand this concept.
    Thanks
    Siddharth

    I have understood that this explanation :
    i) assuming that TimePrinter is an inner class of TalkingClock, that you'd need an instance of the later in order to create an instance of the former.Yes.
    Being a non-static inner class, it can not be instantiated out of context ... which context is the outer class.No. See my reply 11. The "context" is an instance of the outer class - it bears repeating.
    ii) jabberer is the outer instance that you are providing.Yes (more accurately it's a reference to an instance of the outer class, but that would be nit-picking).
    The left side is identifying the class, the right side is identifying the instanceNo.
    I'm not sure what you're calling left side and right side.
    If you're talking about both sides of the equals sign, then no, it's completely wrong.
    If you're talking about both sides of the "point" sign, then it's wrong too, just a bit less wrong.
    Let's revise this step by step (good thought process).
    1. in first line we are getting an outer class reference with this code
    TalkingClock jabberer = new TalkingClock(1000,true);
    this line is very natural and easily understood. Yes. The correct wording would be merely "we are getting a reference to an instance of the outer class". Sorry to insist densely.
    2. Now when we come to the second line, i.e. where we try to instantiate an inner class with this line of code
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    - I do understand the concept that we need an instance of outer class in order to create an instance of inner class as inner class is visible only to outer class.No. We need an instance of the outer class as the inner class is non-static, and by definition needs an instance of the outer class. That has nothing to do with visibility (public vs private vs...). Again, some words have special meanings in the Java world.
    - I also do understand that it cant be instantiated out of context. I see you like this expression, but it is too vague and misleads you. Please forget about it for a moment (no offense to otherwise helpful and knowledgeable abillconsl).
    - I also do understand that left side is identifying the class and right side is identifying the instance. ANDAgain I'm afraid of which "sides" you're talking about.
    - that in this line TalkingClock.TimePrinter listener = new TalkingClock().new TimePrinter();
    the outer class is anonymous (new TalkingClock()) as we don't require its name here Poor choice of words again. Anonymous classes do exist in Java, but are a totally different concept, that is not related to this line.
    - Also in this line TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    I understood the left side part i.e. TalkingClock.TimePrinter listener =
    We are attaching the outer class reference with the inner class that's absolutely understandable. Not at all!
    This just declares a variable listener, whose type is TalkingClock.TimePrinter (or more accurately com.example.innerclass.TalkingClock.TimePrinter).
    Then follows an assignment:
    WHAT I don't understand is the right hand side, i.e., the statement jabberer.new TimePrinter();
    1. I am unable to digest the fact that we can do something like anobject.new
    new is an operator that is used to instantiate an instance of an object. I am unable to digest that we can do x.new?See my previous reply. This is short-hand syntax Sun chose to pass a reference to an instance of the outer class (here, jabberer) to the constructor of the inner class. They could have chosen something else. Again, bear with it.
    I only know that we can do is new SomeClass(); AND NOT instance.new SomeClass();
    Now you know better:
    The second form is valid - only if SomeClass is a non-static inner class defined in a class of which instance is an instance.
    2. Is there something to this conceptually OR this is only a syntax and that I should learn it.
    I want to understand and grasp if there is some concept behind it rather than just learn and mug up. See my previous reply. Each instance of a non-static inner class stores a reference to an instance of the outer class. There must be a way (a syntax) to specify which instance (of the outer class) should be stored in the instance (of the inner class).
    This particular syntax is just a syntax, the "concept" is that the instance of the inner class stores a (unmodifiable) reference to the instance of the outer class that was specified when the instance of the inner class was created.
    I don't know if that deserves to be called a concept, but that's an interesting thing to keep in mind (there are some not-so-obvious implications in terms of, e.g. garbage collection).
    Best regards.
    J.

  • HTML with AWT

    Hi every body !
    Can someone please tell me how I can manage HTML with a AWT component ?
    With Swing, we for example use JEditorPane or JTextPane as I did for a JApplet (http://www.big-chat.com).
    As it is for Applet, I want it to be avalaible in all browsers. But now, it is not the case !
    Please help.
    Thanks !

    Why won't JApplet work in all browsers? Every browser that I know (that is graphical) supports the Java plug-in.
    If you want to support the MS JVM in IE users without the plugin, well there are some things you should know:
    1) MS is not shipping this anymore for newer systems (Win 2003 and XP SP1a).
    2) It's Java version 1.1.4, so there's a whole heck of a lot of stuff that won't work.
    3) It's going to be officially retired in 2007 (was supposed to be in Sept 2004, actually).
    I highly doubt that there's an AWT-based HTML display component out there. There's not one written in Swing that is a complete, up-to-date browser as it is.
    Just stick with the plugin.

  • Technical doubt about setBounds() method

    Hi all.
    I have a little doubt. I don't completely understand the behaviour of setBounds() method of a JComponent extending class.
    I prepared a little test application to explain this doubt. Here it is:
    import javax.swing.*;
    import java.awt.*;
    public class TestSetBounds extends JFrame{
        JPanel myPanel = new JPanel();
        MyComponent myComp = new MyComponent();
        public TestSetBounds() {
            super("SetBounds Test");
            setSize(480, 320);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myPanel.add(myComp);
            setContentPane(myPanel);
            setVisible(true);
        public static void main(String args[]) {
            TestSetBounds tsb = new TestSetBounds();
    class MyComponent extends JComponent implements Runnable
        // setting dimension properties
        int compWidth = 25;
        int compHeight = 50;
        // these values are for testing
        int xStart = 490;
        int xEnd = -12;
        Thread t;
        public MyComponent()
            super();
            setOpaque(true);
            setVisible(true);
            if (t == null)
                t = new Thread(this);
                t.start();
        public void paintComponent(Graphics g)
            super.paintComponents(g);
            setBounds(xStart, 160, compWidth, compHeight);
            Graphics2D area2D = (Graphics2D) g;
            area2D.setColor(Color.RED);
            area2D.fillRect(0, 0, compWidth, compHeight);
        public Dimension getPreferredSize() {
          return new Dimension(compWidth, compHeight);
        public Dimension getMaximumSize() {
          return getPreferredSize();
        public void run()
            for(   ; xStart > xEnd; xStart--)
                repaint();
                try
                    {t.sleep(10);}
                catch (Exception exc) {}
    }   I tested two situations:
    a. Setting xStart = 100 and xEnd = -12, the application run how I expected. With negative value of x coordinate, my component is painted starting out of panel. We only can see my component portion which remains on the panel.
    b. Setting xStart = 490 and xEnd = 300. My component is initially painted out of panel, like test a. During for-cicle, xStart value decreases, entering the panel width value. At this point I must see the component portion which remain on the panel.But the component seems not be painted.
    Why this behaviour?
    Thanks,
    Massimiliano

    Your immediate problem can be solved by making two changes:
    a) your component has no initial size:
    setSize(25, 50); // this is new
    setOpaque(true);
    setVisible(true); // not requiredb) use setLocation() to reposition the component
    setLocation(xStart, 160);
    //repaint(); // not required since changing the location will cause a repaintHowever the code still has many areas of concern.
    For example, after the component has stopped moving, resize the frame. Notice how the component jumps to the top and middle of the frame? This is because by default a JPanel uses a LayoutManager. When you resize the frame the LayoutManager is invoked and the component is positioned based on the rules of the LayoutManager.
    So, you need to read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Using Layout Manager to understand the difference between using a Layout Manager and using "Absolute Positioning" (which is what you are attempting to do).
    You should not be altering the "size" or "location" of the component in the paintComponent() method (ie. get rid of the setBounds()). These changes should be done externally as we did by using the setLocation(..) method.
    When you fill the rectangle you should just use getSize().width and getSize().height, instead of your hard coded variables. Then you can dynamically change the size of your component by using the setSize() method.
    The size of the component should not be hard coded. Once you've made the above change you can simply do:
    MyComponent component = new MyComponent();
    component.setSize(25, 50);

  • Doubt with JMF

    Hi Java Rockers,
    Can any one clarify my doubt?
    I have a doubt in JMF.
    I just wrote a code to play audio and video and
    it was able to play audio and video in windows.
    When i run the same code in Mandriva Linux,
    'I obtained a message "Audio Bus Busy" and it does not played song.
    Actually What went to wrong?
    is it possible to play audio and videos With Java in Linux.?
    Java Version Used:JDK1.6

    Thank you Sir for your
    Suggestion and Help.Here is my Code:
    You please tell me necessary modifications that
    i have to make with this.
    I have 2 classes.
    One as JFrame and others a JPanel.
    JFrame Class:
    import java.net.URL;
    import java.io.File;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    import java.util.Vector;
    import javax.media.*;
    class Media extends JFrame implements Runnable {
    MediaPanel mediaPanel ;
    Thread th;
    JScrollPane scrollPane2;
    Media(){
    MenuBar mbar=new MenuBar();
    Menu m=new Menu("File");
    MenuShortcut sc1=new MenuShortcut(KeyEvent.VK_O);
    MenuItem m1=new MenuItem("Open",sc1);
    m1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
                   if(th!=null)
                        th.stop();
                   else{
                   Frame fr=new Frame();
                   FileDialog fd=new FileDialog(fr,"Open");
                   fd.setDirectory("E:\\songs");     
                   fd.setVisible(true);
                   try{
                   String name="file:\\"+fd.getDirectory()+"\\"+fd.getFile().toString();
                   URL mediaURL =new URL(name);
                   mediaPanel= new MediaPanel( mediaURL );
                   int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
                   int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
                   scrollPane2=new JScrollPane(mediaPanel,v,h);
                   setLayout(new BorderLayout());
                   getContentPane().add(scrollPane2,BorderLayout.CENTER);
                   if ( mediaURL != null ) {
                        mediaPanel.setVisible(true);
                        scrollPane2.setViewportView(mediaPanel);
                   repaint();
                   setSize(470,360);
                   //refresh_preview(new URL("file:\\"+fd.getDirectory()+"\\"+fd.getFile().toString()));
                   catch(Exception E){
                   JOptionPane.showMessageDialog(null,"Failed to play!"+"\n"+"Reason:"+"\n"+E.toString(),"Error",JOptionPane.ERROR_MESSAGE);
    MenuShortcut sc3=new MenuShortcut(KeyEvent.VK_E);
    MenuItem m3=new MenuItem("Exit",sc3);
    m3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              dispose();
    m.add(m1);
    m.add(m3);
    Menu Help=new Menu("Help");
    MenuShortcut hc1=new MenuShortcut(KeyEvent.VK_H);
    MenuItem H1=new MenuItem("About",hc1);
    H1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         JOptionPane.showMessageDialog(null,"Java ™ Media Player!","Version Info.. :",JOptionPane.INFORMATION_MESSAGE);
    MenuShortcut hc2=new MenuShortcut(KeyEvent.VK_Q);
    MenuItem H2=new MenuItem("JMF Installation Procedures",hc2);
    H2.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmf.htm");
    MenuShortcut hc3=new MenuShortcut(KeyEvent.VK_S);
    MenuItem H3=new MenuItem("JMF Supportive File Formats",hc3);
    H3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmfdoc.htm");
    Help.add(H1);
    Help.add(H2);
    Help.add(H3);
    mbar.add(m);
    mbar.add(Help);
    setMenuBar(mbar);
    JLabel jl=new JLabel("Java Media Player",SwingConstants.CENTER);
    getContentPane().add(jl,BorderLayout.SOUTH);
    setSize(600,300);
    setTitle("Video/Audio Player in java");
    setVisible(true);
         Toolkit kit = Toolkit.getDefaultToolkit();
         Dimension screenSize = kit.getScreenSize();
         int screenWidth = screenSize.width;
         int screenHeight = screenSize.height;
         java.awt.Image img = kit.getImage("images//audio-category.jpg");
         setSize(screenWidth /2, screenHeight / 2);
         setLocation(screenWidth /4, screenHeight /4);
         setIconImage(img);
    Media(URL media_file){
    MenuBar mbar=new MenuBar();
    Menu m=new Menu("File");
    MenuShortcut sc1=new MenuShortcut(KeyEvent.VK_O);
    MenuItem m1=new MenuItem("Open",sc1);
    m1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
                   if(th!=null)
                        th.stop();
                   else{
                   Frame fr=new Frame();
                   FileDialog fd=new FileDialog(fr,"Open");
                   fd.setVisible(true);
                   try{
                   String name="file:\\"+fd.getDirectory()+"\\"+fd.getFile().toString();
                   URL mediaURL =new URL(name);
                   mediaPanel= new MediaPanel( mediaURL );
                   int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
                   int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
                   scrollPane2=new JScrollPane(mediaPanel,v,h);
                   setLayout(new BorderLayout());
                   //JLabel jl=new JLabel("Java Media Player",SwingConstants.CENTER);
                   //getContentPane().add(jl,BorderLayout.SOUTH);
                   getContentPane().add(scrollPane2,BorderLayout.CENTER);
                   if ( mediaURL != null ) {
                        mediaPanel.setVisible(true);
                        scrollPane2.setViewportView(mediaPanel);
                   catch(Exception E){
                   JOptionPane.showMessageDialog(null,"Failed to play!"+"\n"+"Reason:"+"\n"+E.toString(),"Error",JOptionPane.ERROR_MESSAGE);
    MenuShortcut sc3=new MenuShortcut(KeyEvent.VK_E);
    MenuItem m3=new MenuItem("Exit",sc3);
    m3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              dispose();
    m.add(m1);
    m.add(m3);
    Menu Help=new Menu("Help");
    MenuShortcut hc1=new MenuShortcut(KeyEvent.VK_H);
    MenuItem H1=new MenuItem("About",hc1);
    H1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         JOptionPane.showMessageDialog(null,"Java ™ Media Player!","Version Info.. :",JOptionPane.INFORMATION_MESSAGE);
    MenuShortcut hc2=new MenuShortcut(KeyEvent.VK_Q);
    MenuItem H2=new MenuItem("JMF Installation Procedures",hc2);
    H2.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmf.htm");
    MenuShortcut hc3=new MenuShortcut(KeyEvent.VK_S);
    MenuItem H3=new MenuItem("JMF Supportive File Formats",hc3);
    H3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmfdoc.htm");
    Help.add(H1);
    Help.add(H2);
    Help.add(H3);
    mbar.add(m);
    mbar.add(Help);
    setMenuBar(mbar);
    JLabel jl=new JLabel("Java Media Player",SwingConstants.CENTER);
    URL mediaURL = null;
    mediaURL = media_file;
    mediaPanel= new MediaPanel( mediaURL );
    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    scrollPane2=new JScrollPane(mediaPanel,v,h);
    setLayout(new BorderLayout());
    getContentPane().add(scrollPane2,BorderLayout.CENTER);
    getContentPane().add(jl,BorderLayout.SOUTH);
    if ( mediaURL != null ) {
    mediaPanel.setVisible(true);
    scrollPane2.setViewportView(mediaPanel);
    setSize(600,300);
    setTitle("Video/Audio Player in java");
    setVisible(true);
         Toolkit kit = Toolkit.getDefaultToolkit();
         Dimension screenSize = kit.getScreenSize();
         int screenWidth = screenSize.width;
         int screenHeight = screenSize.height;
         java.awt.Image img = kit.getImage("images//audio-category.jpg");
         setSize(screenWidth /2, screenHeight / 2);
         setLocation(screenWidth /4, screenHeight /4);
         setIconImage(img);
    void init(){
    public void refresh_preview(URL media_file){
    URL mediaURL = null;
    mediaURL = media_file;
    if ( mediaURL != null ){
    MediaPanel mediaPanel = new MediaPanel( mediaURL );
    mediaPanel.setVisible( true );
    scrollPane2.setViewportView(mediaPanel);
    public void run(){
    try{
    th.stop();
    catch(Exception E){}
    **JPanel Class:**
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.net.URL;
    import javax.media.CannotRealizeException;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    public class MediaPanel extends JPanel
    JLabel l=new JLabel();
    public MediaPanel( URL mediaURL ){
    setLayout( new BorderLayout() ); // use a BorderLayout
    // Use lightweight components for Swing compatibility
    Manager.setHint( Manager.PLUGIN_PLAYER, new Boolean(false));
    try
    // create a player to play the media specified in the URL
    Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
    // get the components for the video and the playback controls
    Component video = mediaPlayer.getVisualComponent();
    Component controls = mediaPlayer.getControlPanelComponent();
    if ( video != null )
    add( video, BorderLayout.CENTER ); // add video component
    else{
    add(l);
    l.setIcon(new ImageIcon("images\\black.jpg"));
    if ( controls != null )
    add( controls, BorderLayout.SOUTH ); // add controls
    mediaPlayer.start(); // start playing the media clip
    } // end try
    catch ( NoPlayerException e ){
    System.err.println( "No media player found" );
         JOptionPane.showMessageDialog(null,"Reason:"+"\n"+e.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
    catch ( CannotRealizeException c ){
    System.err.println( "Could not realize media player" );
         JOptionPane.showMessageDialog(null,"Reason:"+"\n"+c.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
    catch ( IOException i ){
    System.err.println( "Error reading from the source" );
         JOptionPane.showMessageDialog(null,"Reason:"+"\n"+i.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
    ]

  • Tutorial on AWT/Swing control flow

    Greetings all,
    Just wondering if any of you folks know of a good tutorial on AWT/Swing control flow? I'm doing some pretty complex stuff with a table whose editors call other windows and insert values into the table based on callback objects...weird stuff happening with loss of focus when the other windows come out, etc etc etc.
    I have it working via a series of what I consider kludges, but I would really like to implement it cleanly, and it's looking like that's going to require understanding <ugh> <grin>
    So it looks like it's time that I bit the bullet and got to grips with control flow in AWT/Swing. Is there a tutorial out there that could help me with this?
    Many TIA

    skiaddict1 wrote:
    Let's take your word for it, but if you have the slightest doubt please consider the subject: EDT violation is a classic here.OK sure, but I really don't think I'm violating it. I avoid multi-threading like the plague, and only introduced it for my report writer because I wanted to have a little window advising the user that the report was in the process of being written.Raise your left hand and swear this report writer is not running when you experience the problem you describe! >o(
    OK, this is just kidding, as per the rest of your description, it sounds reasonable now to assume that your problem is not related to EDT violation.
    I'm doing some pretty complex stuff with a table whose editors call other windows and insert values into the table based on callback objects...This summary is a bit worrying, and I thought you would mention problems in the display of the table being edited. But you seem to refer to problems in other windows, or did I misunderstand?
    Or do you mean, loss of focus in the editor still being edited? Can you please clarify what you do and what your problems are?
    In particular, what does the other windows come out mean?OK, I was trying to be sparse with details because I didn't think they were relevant.Actually the worrying seems all the more justified, now that you have described it more extensively: I was afraid that you would raise other windows while editing, and that's the case. I know little of focus though...
    I have a table in window A, one of whose columns has a custom editor which, when a cell in the column is double-clicked, registers itself with window B as a choice-listener (see later) then asks window B to come to the front. Window B, when the user performs a choice amongst the UI elements in there, fires a choice-event to its listener, i.e. the custom editor. At which point the editor saves away the chosen value (for use by getCellEditorValue()), sets the text in the cell appropriately, turns edit mode off via fireEditStopped(), and brings window A back to the front.
    (...) once the custom editor asks window B to come to the front, the table in window A loses focus and when it is brought back to the front, the table's JScrollPane seems to have the focus (visually, it has the focus rectangle around it). Pressing the Tab key has no effect on focus; you have to use the mouse to focus something.I assume you have read the tutorial on using tables in Swing.
    It contains an example where a custom editor is bringing up a dialog: http://download.oracle.com/javase/tutorial/uiswing/components/table.html#editor
    AFAIK, the example does not suffer from focus problems.
    What I am finding, and I reiterate this is new since I rewrote the windowing subsystem for the app (the custom editor was not changed in the rewrite), is that (...)Just what do you call "rewriting the windowing system" (just to rule out the possibility of something Ramboesque)?
    I have no idea why this loss of focus is occurring, and I am at a loss to begin to figure it out. As I wrote above, I have a series of kludges which gets around the symptoms, but I would really rather figure it out and fix it.OK I admit I cannot tell what happens exactly, but:
    1) instead of bringing window B to front, couldn't the editor bring up a dialog B (e.g. using JOptionPane.showXxxDialog() to bring up just the choice panel? The advantage is that it is more "synchronous", you can control when the window A's table model is updated.
    2) what worries me too is that you update the model of the table being edited while you're editing one cell of it? Would it be possible, and make sense in your case, to update this model later (that is, post the model update as an invokeLater(...) call)? I don't see how seeing the table updating underneath helps the user editing its cell, but you may have your reasons.
    What do you call flow control , or control flow in AWT/Swing?Basically, what I am after is something that will help me begin to understand/diagnose problems such as the above when they happen in my code. I am deeply averse to multi-threading (...) Things in my code were working, and that was enough for me.
    But the above behaviour, and another weird behaviour I was having last week, which again I have solved with what I consider a kludge, and again which only began with my new windowing subsystem, have caused me to realise that it's time I really got to grips with this issue.Yes, when they say beware of threads when using Swing , nobody tells to not use threads! Just to be aware of how special Swing is with regards to threads (at least, compared to AWT, that didn't make such warning).
    I would like, for example, to really deep-down understand exactly when listeners for AWT-Swing events get called. I don't really care so much when the events get put on the queue, but I do care when exactly my event handlers will be called. This will help me diagnose problems, I'm sure.Well they get called in the EDT, by some framework code that, in an infinite loop, does something along the lines of:
    - pop next event from the event queue
    - determine which is the target widget
    - let the widget transform the event and send it to all registered listeners
    Now with dialogs, things gets dimmer, because while a dialog is brought up (via a<tt>setVisible(true)</TT> call on the EDT, the EDT is indeed suspended, and a new event thread manages the events for the dialog).
    I'm sorry I have no reference for that behavior, and my description is certainly blurry (and possibly wrong), but I don't think your problem is so much related to threading as I initially thought.
    N.B.: Darryl's second link does features sequence diagrams that try to demonstrate what happen (in a specific example with asynchronous access, but you can derive the simpler, regular, working, from it).OK, yes I saw that diagram, I was offput by the asynchronicity but I will have another look tomorrow also. Thanks againDon't put too much hopes in there, indeed it's definitely not the kind of info I understand you're looking after.
    Much luck all the same, and feel free to come back with your findings, or with more questions, about the initial subject (reference on event flow) and the specific problem (your focus issues with the editor).
    I also cannot end this message without suggesting that you try to reproduce the problem with an SSCCE (http://sscce.org), that you could post here for us to try out. See this recent discussion about the multiple interests of this approach: {message:id=9587964}
    Best regards,
    J.

  • SetToolTipText() in AWT ??

    Hi
    In Swings we have setToolTipText(String)��to display some Tip Text.
    Similarly is there any think like that in AWT ??
    thanksinadvance
    Yours
    Rajesh

    Hi
    Recently I found Code to Display Tool Tip Text in AWT
    You can make use of following 2 program codes
    With this code you can set the tooptip for AWT or Applet
    if u got doubts pl ask me.
    First Program
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    public class ToolTip extends Canvas {
         protected String tip;
         protected Component owner;
         private Container mainContainer;
         private LayoutManager mainLayout;
         private boolean shown;
         private final int VERTICAL_OFFSET = 30;
         private final int HORIZONTAL_ENLARGE = 10;
    public ToolTip(String tip, Component owner) {
         this.tip = tip;
              this.owner = owner;
         owner.addMouseListener(new MAdapter());
              setBackground(new Color(255,255,220));
         public void paint(Graphics g) {
              g.drawRect(0,0,getSize().width -1, getSize().height -1);
              g.drawString(tip, 3, getSize().height - 3);
         private void addToolTip() {
              mainContainer.setLayout(null);
              FontMetrics fm = getFontMetrics(owner.getFont());           
              setSize(fm.stringWidth(tip) + HORIZONTAL_ENLARGE, fm.getHeight());
              setLocation((owner.getLocationOnScreen().x - mainContainer.getLocationOnScreen().x) ,
                             (owner.getLocationOnScreen().y - mainContainer.getLocationOnScreen().y + VERTICAL_OFFSET));
              // correction, whole tool tip must be visible
              if (mainContainer.getSize().width < ( getLocation().x + getSize().width )) {
                   setLocation(mainContainer.getSize().width - getSize().width, getLocation().y);
              mainContainer.add(this, 0);
              mainContainer.validate();
              repaint();
              shown = true;
         private void removeToolTip() {
              if (shown) {
                   mainContainer.remove(0);
                   mainContainer.setLayout(mainLayout);
                   mainContainer.validate();
              shown = false;
         private void findMainContainer() {
              Container parent = owner.getParent();
              while (true) {
                   if ((parent instanceof Applet) || (parent instanceof Frame)) {
                        mainContainer = parent;
                        break;                    
                   } else {
                        parent = parent.getParent();
              mainLayout = mainContainer.getLayout();
    class MAdapter extends MouseAdapter {
         public void mouseEntered(MouseEvent me) {
              findMainContainer();
              addToolTip();
         public void mouseExited(MouseEvent me) {
              removeToolTip();
              public void mousePressed(MouseEvent me) {
              removeToolTip();
    Second Program
    <applet code="ToolTipTest.class" width=300 height=300></applet>
    import java.awt.*;
    import java.awt.event.*;
    public class ToolTipTest extends java.applet.Applet {
         private Label myLabel;
         private Button myButton;
         private TextField myTextField;
    public void init() {
         myLabel = new Label("Hello world!");
         new ToolTip("I say: Hello world!", myLabel);
         myButton = new Button("Press");
         new ToolTip("It's working !", myButton);
         myTextField = new TextField(10);
         new ToolTip("Tip for this field", myTextField);
         add(myLabel);
         add(myButton);
         add(myTextField);
    Ok Thankyou VeryMuch
    Yours
    Rajesh

  • Applet doubt

    I m taking this code from else where .but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here
    java code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class LoginApplet2 extends JApplet {
    public void init() {
    add( new MainGui(), BorderLayout.CENTER );
    validate();
    public static void main(String[] args) {
    Runnable r = new Runnable() {
    public void run() {
    JFrame f = new JFrame("Log-In app.");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.add( new MainGui(), BorderLayout.CENTER );
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
    SwingUtilities.invokeLater(r);
    class MainGui extends JPanel {
    JButton logIn;
    JLabel status;
    JPasswordField passwordField;
    JTextField username;
    JLabel logInLabel;
    JPanel mainPanel;
    JPanel usernamePasswordPanel;
    CardLayout cards;
    MainGui() {
    super.setLayout(new BorderLayout(3,3));
    status = new JLabel("Log-In to proceed");
    add(status, BorderLayout.NORTH);
    mainPanel = new JPanel();
    cards = new CardLayout();
    mainPanel.setLayout(cards);
    usernamePasswordPanel = new JPanel(new GridLayout(2,2,3,3));
    usernamePasswordPanel.add( new JLabel("Username:") );
    username = new JTextField(10);
    usernamePasswordPanel.add( username );
    usernamePasswordPanel.setBorder(new EmptyBorder(25,25,25,25));
    usernamePasswordPanel.add( new JLabel("Password:") );
    passwordField = new JPasswordField(10);
    usernamePasswordPanel.add( passwordField );
    logInLabel = new JLabel("Log In to use the app.");
    mainPanel.add(logInLabel,"login");
    JPanel mainApp = new JPanel(new BorderLayout(3,3));
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    mainApp.add(new JTextArea(4,20), BorderLayout.CENTER);
    mainPanel.add(mainApp, "app");
    logIn = new JButton("Log In");
    logIn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae) {
    if (logIn.getText().equals("Log In")) {
    JOptionPane.showMessageDialog(
    logIn,
    usernamePasswordPanel,
    "Log-In (Pswd hint: any 4+ letters or digits)",
    JOptionPane.QUESTION_MESSAGE);
    checkPassWord();
    } else {
    logOut();
    add(logIn, BorderLayout.SOUTH);
    add(mainPanel, BorderLayout.CENTER);
    setBorder(new EmptyBorder(4,4,4,4));
    public void checkPassWord() {
    // change this for server based authentication
    if (passwordField.getPassword().length>3) {
    cards.show(mainPanel, "app");
    logIn.setText("Log Out");
    status.setText("Logged in as " + username.getText());
    } else {
    status.setText("Log In failed!");
    public void logOut() {
    cards.show(mainPanel, "login");
    logIn.setText("Log In");
    status.setText("Logged out");
    passwordField.setText("");
    related html::
    <html>
    <head></head>
    <body>
    <applet code="LoginApplet2.class" width=300 height=300>
    </applet>
    </body>
    </html>

    >
    I m taking this code from else where . ..>Where? If it is available on the net, it is better to give the URL.
    And whenever pasting code, code snippets, HTML/XML or input/output, please use the code tags. The code tags help preserve the indentation and formatting of the text. To use the code tags, select the text and click the CODE button on the Plain Text tab of the message posting form.(1)
    >
    .. but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.>Please spell words fully(2). For the sake of saving typing a couple of letters, it makes people seem like buffoons.
    >
    ...If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here >
    - (2) Those words are 'please' and 'you'.
    - The word I should always be upper case. Always.
    - Please add 2 spaces and a single upper case letter at the start of every sentence. This helps the reader, and you would not want to make it harder for people to help you, would you?
    - "If i want my own menu how can i do this" is a question, and should be 'marked' as a question with a question mark -> "If I want my own menu how can I do this?".
    - And since it came up - 'doubt' seems to be an Indian(/English) word for 'question'. These are international forums, so that subject should be 'applet question'
    - It is not a good idea to invite people on public forums to tutor you privately. It is generally felt that public forums are also to help people 'searching' for the answer later, and if a thread goes to email, that opportunity is lost.
    - Posting an email address to a public forum will attract a torrent of spam.
    But the 'short answer' to your question is..
    >
    java code:
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);>..Use one of the [JTree constructors|http://java.sun.com/javase/6/docs/api/javax/swing/JTree.html#constructor_summary] *(<- link)* that accepts an argument. For further details, see [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html] *(<- link)* in the Java Tutorial.
    (1) And here is how that snippet looks when inside code tags
        mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    ...

  • If Statement in java.awt paint

    import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of Bmi classI have written the above code to calculate someones BMI (Body Mass Index). Basically as you can see it recieves a weight and height from the user and calculates the rest. But whilst that good I would like to know how I can make it tell the user something to the effect of "Your overweight" or "Your underweight". The if statement runs like this:
    if (wt > max)This forum doesn't quite handle <> properly. The greater and less than symbols. So above you will see > this is the html character code for a greater than symbol so please read it as such.
    And then if wt is greater than max then it will say "Your overweight".
    But I can't figure out how to include it in the above program. Becuase it won't run in paint, atleast it won't the way I have done it previously. So can you think of any other ways?
    Help much appreciated,
    Simon

    Thanks very much that works well.
    Simon
    My code now looks like this: import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void you(Graphics g)
      String statement;
      if(wt > max) statement="You are very fat";
      else if(wt < min) statement="You are very thin";
      else statement="You are in the recommended weight range for your height";
      g.drawString(statement, 20,210);
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        you(g);
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of BmiThanks again,
    Simon

  • Doubt in fbl1n transaction

    hi i have a doubt....
    in fbl1n transaction, there are open items and cleared items.
    in it the cleared items  for certain document types such as invoice etc is not present in the open item table (bsik)
    however the cleared items for document types such as general  voucher its present in the open items table (bsik)
    is this possible as all cleared item entries shld b present in the open item table with an indicator set for cleared or not...
    plz exlain!

    Hi
    There are 2 tables(open and Closed Items)  in FI for Account Payables and Account Receivables and GL accounts
    1.Account payables: BSIK is Open Items and BSAK is Closed items
    2.Account Receivables; BSID and BSAD for OPEN and closed items
    3/GL accounts :  BSIS and BSAS  for Open and Closed Items
    <b>Reward points for useful Answers</b>
    Regards
    Anji

  • Can I build a GUI application with SWING only without [import java.awt.*;]

    I have seen several threads (in forums), books and tutorials about SWING and I see that they all mix SWING with AWT (I mean they import both Swing and AWT in their code).
    The conclusion that comes out is:
    It is good to learn about SWING and forget AWT as it won't be supported later. I have decided to do so, and I never include <<import java.awt.*;>> in my code.
    But I see that you cannot do much without <<import java.awt.*;>>. For example this line which changes the background color:
    <<frame.getContentPane().setBackground(Color.red)>>
    works only with <<import java.awt.*;>>. I have seen that codes in this and other forums import awt to change the background. Why is that?
    After all, I wonder, what can I do;
    My question is, can I change the background (and of course do all other things listener, buttons etc) without using <<import java.awt.*;>>.
    I would like to avoid using <<import java.awt.*;>> and using awt since my program will not work later.
    In addition, I believe there is no point to learn awt, which later will not exist.
    I know, I must have misunderstood something. I would appreceate it very much, if anyone could give me even a short answer.
    Thank you in advance,
    JMelsi

    Since swing is a layer on top of awt, AWT will exist for as long as swing does.
    If sun does ever remove AWT they will have to replace it something else swing can layer on to and you will probably only have to replace your import statements.
    The main difference is the way there drawn to the screen.
    You can do custom drawing on swing components but you can't on AWT.
    If your using a desktop PC system it's probably best to use swing just in case you wish to do some custom drawing.
    awt uses less memory than swing and is faster but swing can be extended. awt comes only as standard.
    Say for example you wish to implement a JButton with a ProgressBar below the button text, this can be done with swing!

  • Doubt in creation of a new object

    Hi All,
                 I have one doubt in creation of a new object.If a new object is to be created and it is not a subtype
    of any existing object, then what should we enter in the Program field for creating the object?
    I hope I am clear with my question.
    Thanks in Advance,
    Saket.

    Hi Saket,
    Following will be required for created a custom business object.
    1. Object Type - ZTEST (Internal Techincal Key)
    2. Object Name - ZTESTNAME (Technical Key Name)
    3. Name - TEST (Name of BO, it is used while selecting the object type)
    4. Description - (Short Description of BO)
    5. Program - ZTESTPROGRAM (ABAP program in which the methods of the object type are implemented)
    6. Application - A or B.. etc (Area to which your BO is related)
    Please remember that you can learn these basic things by giving F1 help on those fields and in HELP.SAP.COM.
    Regards,
    Gautham Paspala

Maybe you are looking for