Object life in main method after frame created

hi
i'm having a slight problem with the life of an object i'm creating in the main method of my application.
i have a JDesktopPane that is initialised in the main class's main method and constructor. within the main method i also add the first internal frame to the desktop.
after the user completes the details of the first frame, another is called (from this first frame) and the first frame is disposed.
the problem is that although all subsequent internal frames added to the desktop outside the main class, they are garbage collected with no problems (i'm using a profiler), however the first frame and the frame created from that first frame are never collected due to the reference maintained in the main class. i've tried adding the creation of these frames outside the main class but given that these methods are called from main the reference is still maintained.
is there any way to create those first 2 frames without the reference being maintained in the main class such that they become elegible for garbage collection? do i have it all wrong perhaps and my approach is bad?? any help would be greatly appreciated.
thanks heaps.
Takis

hi
thanks for your reply.
i tried that and it didn't work. the instance of that first internal frame is still there.
i really am at a loss with this one.
any other suggestions would be greatly appreciated.
Takis

Similar Messages

  • Any way (event) to call Java method after view created in JSF 2.0

    Hi,
    I am using JSF 2.0 Mojarra's implementation.
    I am interested to know if there is a way to call Java methods before and/or after view has been restored.
    I wanted to initialize data for my page in this Java method.
    I could see there is an event class PostRestoreStateEvent added in JSF 2.0. How to use it?
    I tired to use f:event element as below, but it does not work. Can anyone share anyother idea to achieve this behaviour?
    <f:metadata>
    <f:event type="postRestoreState" listener="#{employeeLoadBean.loadAfterRestoreView}"/>
    </f:metadata>
    Regards,
    Kishore K S

    Hi,
    The problem is solved as below.
    <f:metadata>
    <f:event type="javax.faces.event.PostRestoreStateEvent" listener="#{employeeViewEventListener.postRestoreState}"/>
    </f:metadata>
    The above calls the Java method #{employeeViewEventListener.postRestoreState} whenever View has been restored.
    It was not working when shortName of the event (ie., postRestoreState) is given and throwing ClassNotFound exception.
    Regards,
    Kishore K S

  • Running a java application without a main method

    class MainMethodNot
        static
            System.out.println("This java program have run without the run method");
            System.exit(0);
    }The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.
    got it from http://www.java-tips.org/

    This has been published many times on this forum. What is your question?

  • Why CreateNewFrame() returns as NULL after successful created 136 child frame window and trying to create 137th child frame window in MDI application

    I am working on MDI application which was developed in VC++ in VS 2012. When my application is launched, it will display a Tree. Under a tree there are 254 nodes. Basically
    these nodes data are read from Configuration xml file and loaded into the Tree. By double clicking on each node, first it will create object for document class ( By calling CreateNewDocument() method) after that member variables for that
    document class will be initialized and then it will create the new frame window (by calling
    CreateNewFrame(pDoc,NULL). New child frame window will show under Main window to the user.
    User able to see the data from child frame window.
    Similarly by double clicking on each node it will create another object for the same document class and new child frame window will be opened for that node. Each child frame window runs
    in different data and showed under the Main window.
    Existing requirement by double clicking on each node, node data shall show in separate child window and there is no requirement for all 254 child windows opened simultaneously.
    But current requirement is , all 254 child windows shall open simultaneously by double clicking on each node one by one.
    In debug mode I have tried double clicking on each node. I able to open up to 50 nodes. After 50th child windows are opened, I unable to access to the application
    (Unable to open further node data window since application is getting hanged).
    Each child window is having tree, multiple splitter window and some additional controls (static text, ...).
    Same I have tried in release mode, I able to open up to 136 child windows. After that the application fail to create the new frame window in VS 2012. i.e CreateNewFrame() return
    NULL after successful created 136 child frame window. Debug purpose I have added the code to retrieve last error code by calling GetLastError() method. I got the value as "0". By closing any existing child window then I able to open remaining nodes.
    At any point of time I can reach maximum of 136 child frame window that can be opened under Main window. Failing to open all 254 child frame window
    simultaneously,  currently I fail to meet the current requirement.
    current Requirement is all 254 child frame window are opened simultaneously. Please let me know what may be the reason fail to create new frame window after 136 frame window that are
    opened already. In Microsoft site, mentioned that there is no limitation for creating frame  window in MDI application. I have tried another sample MDI application having limited number of controls, in which I able to create "n"
    number of child frame windows. why not able to create more than 136 child frame window in my actual application?
    Is there any possibility by changing project settings allow me to create 254 child frame window??
    Code Snippet as below:
    CDiagBaseDoc * CDiagBaseMDocTemplate::OpenDiagView( ...)
         CDiagBaseDoc* pDoc = NULL;
        if (pDoc == NULL)
            pDoc = (CDiagBaseDoc*)CreateNewDocument();
        if ( pDoc )
           CFrameWnd* pFrame = NULL;
           if (bAlreadyOpen)
                  // If Child frame window already opened, then handling the code here.
         else
               pFrame = CreateNewFrame(pDoc, NULL);
               if (pFrame == NULL)
                  ASSERT(FALSE);
                  delete pDoc;       // explicit delete on error
                 pDoc = NULL;
              ASSERT_VALID(pFrame);
              if( pDoc != NULL ) //VS2012
                 if ( !pDoc->OnNewDocument() )
                    TRACE0("CDocument::OnNewDocument returned FALSE\n");
                    delete pDoc;       // explicit delete on error
                    pDoc = NULL;
                    pFrame->DestroyWindow();
                     pFrame = NULL;
           if (pFrame)
               InitialUpdateFrame(pFrame, pDoc);
               ShowWindow( pFrame->GetSafeHwnd(), SW_MAXIMIZE ); //when opening node for the 1st time, maximize it
    }<o:p></o:p>

    Hi MuruganK,
    Have you checked how much memory your application used? You could check it by Task Manager. Maybe your application reach Memory Limits for Windows.
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa366778%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
    Is it possible that there are some memory leaks in your application? It would better if you have made a simple sample to reproduce and narrow down this issue.
    Best regards,
    Shu
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Class extending a Frame with main method in it - how do I use the methods?

    Howdy.
    Having a problem.. I want my "main" class, ie. the class with the main method in it to extend a Frame class.. because the main method is static, I can't use Frame's methods.
    What's a trick to get around this ? I am making a deliberate design decision to extend the Frame class, because I thought it was.. well.. better. I could always just create a Frame object and utilise it.. but from little things I've read and seen it's better to extend it.
    When I use Forte to make a Frame program it sets up a constructor/etc. for the main class and then it does something akin to this (the class is called MazeGenerator) :
    public static void main(String args[]) {
    new MazeGenerator().show();
    What does "new MazeGenerator().show();" do when it's not being associated to an object handle ??
    Ta.
    - Scutt.

    Create an instance of the frame in main then the constructor can control it. Or you could add an init method or something:
    class MyFrame extends Frame {
    public static void main (String [] args) {
    MyFrame frame = new MyFrame();
    frame.init();
    You don't necessarily have to have a reference to an Object in order to create one. All the work can be done in the constructor (something I'm not really fond of however)

  • Get row id after EJB create method.

    Hi,
    does any one know how to get an id of new created by CMP ejb row? When I create new object it's id is 0, when i call ejb create it creates new row in DB and crates new ID by increasing the old one, but how can I get this new ID after create has finished?
    Now I have to look equals by some fields object in DB after creation, looks ugly.

    So here is my CMP :
    * @ejb.bean name="Dividend"
    * type="CMP"
    * view-type="local"
    * primkey-field="id"
    * schema="dividends"
    * cmp-version="2.x"
    * @ejb.value-object name="Dividend"
    * match="*"
    * @ejb.transaction type="Required"
    * @ejb.persistence table-name="dividends"
    * @ejb.finder signature="Collection findAll()"
    * query="SELECT OBJECT(d) FROM dividends d"
    * @jboss.query signature="Collection findAll()"
    * @ejb.finder signature="Dividend findByActivityId(java.lang.Integer activityId)"
    * query="SELECT OBJECT(d) FROM dividends d WHERE d.activityId = ?1"
    * @jboss.query signature="Dividend findByActivityId(java.lang.Integer activityId)"
    * strategy="on-load"
    * @jboss.persistence create-table="false"
    * remove-table="false"
    * datasource="java:/ChronimDS"
    * datasource-mapping="mySQL"
    public abstract class DividendBean implements EntityBean {
    //~ Methods ----------------------------------------------------------------
    //==========================================
    // Business methods
    //==========================================
    * @ejb.interface-method
    public Dividend getDividend() {
    Dividend dividend = new Dividend();
    dividend.setId(this.getId());
    dividend.setActivityId(this.getActivityId());
    dividend.setLower(this.getIsLower());
    dividend.setLowerAmount(this.getLowerAmount());
    return dividend;
    * @ejb.interface-method
    public void setDividend(Dividend dividend) {
    this.setActivityId(dividend.getActivityId());
    this.setIsLower(dividend.isLower());
    this.setLowerAmount(dividend.getLowerAmount());
    //==========================================
    // CMP fields
    //==========================================
    * @ejb.pk-field
    * @ejb.persistence column-name="id"
    * jdbc-type="INTEGER"
    * sql-type="INTEGER"
    * @ejb.interface-method
    * @ejb.transaction type="NotSupported"
    public abstract Integer getId();
    public abstract void setId(Integer id);
    * @ejb.persistence column-name="activityId"
    * jdbc-type="INTEGER"
    * sql-type="INTEGER"
    public abstract Integer getActivityId();
    public abstract void setActivityId(Integer activityId);
    * @ejb.persistence column-name="isLower"
    * jdbc-type="TINYINT"
    * sql-type="TINYINT"
    public abstract boolean getIsLower();
    public abstract void setIsLower(boolean isLower);
    * @ejb.persistence column-name="lowerAmount"
    * jdbc-type="INTEGER"
    * sql-type="INTEGER"
    public abstract Integer getLowerAmount();
    public abstract void setLowerAmount(Integer lowerAmount);
    //==========================================
    // EJB callbacks
    //==========================================
    * @ejb.create-method
    public Integer ejbCreate(Dividend dividend)
    throws CreateException {
    this.setId(dividend.getId());
    this.setIsLower(dividend.isLower());
    this.setLowerAmount(dividend.getLowerAmount());
    this.setActivityId(dividend.getActivityId());
    return null;
    public void ejbPostCreate(Dividend dividend)
    throws CreateException {
    // EntityBean (empty) implementation
    public void setEntityContext(javax.ejb.EntityContext ec) {
    public void unsetEntityContext() {
    public void ejbLoad() {
    public void ejbStore() {
    public void ejbActivate() {
    public void ejbPassivate() {
    public void ejbRemove() {
    As you can see I'm using xdoclets.
    Suppose I need to create new row of this object :
    Dividend d = new Dividend();
    // fill dividend by values here but do not set it's id it is 0 before creation
    // SQL server will set it automaticly
    Object ref = context.lookup("DividendLocal");
    DividendLocalHome dividendLocal = (DividendLocalHome) ref;
    dividendLocal.create(dividend)
    I create new row of dividend in my DB and want to get an ID of the new created row, I thought that dividend object will get this ID after creation automaticly, but no, his id is 0.
    so here id will be 0 :
    dividendLocal.create(dividend);
    int id = dividend.getId(); // 0
    and if I write this
    dividendLocal.create(dividend).getId();
    I get :
    2007-06-25 14:44:02,384 ERROR [org.jboss.ejb.plugins.LogInterceptor]
    EJBException in method: public abstract java.lang.Integer
    com.xxx.xxx.ejb.SessionFacade.createDividend(
    xxx.xxx.model.Contract) throws java.rmi.RemoteException:
    javax.ejb.NoSuchObjectLocalException: Entity not found: primaryKey=0

  • How many methods copies will create when i create multiple objects

    Hi
    I have big doubt in java. See the following Program
    class A{
    public int i;
    public static int j;
    public void methodOne(){
    Sytem.out.println("Welcome");
    public static void methodTwo(){
    System.out.println("Welcome methodOne");
    class B{
    public static void main(String[] args){
    A obj = new A();
    A objOne = new A();
    A objTwo = new A();
    In this program how many method copies and variable copies will create when i create mulitiple objects. I am sure that only one copy j variable and methodTwo method (becz both are static) for all the objects. what about the method methodOne and i. Here how many copies will create. Could you please explain this concept very clearly.
    Thanks and Regards
    Sherin Pooja

    Sherin wrote:
    Sorry I pasted the previous comment with table format. Here the table format is not working
    Local variables---Stack     
    Instance/Member/field variables---Heap     
    Class/static variables---Static Memory
    Methods---Methods do not live on the heap or stack.Incorrect. Methods live in the method area, which is "logically part of the heap," according to the JVM spec.
    Instance/Member/field variables---It will create and destroy according to object initialization and destroy.That's very poor English and doesn't really capture what happens.
    policyHolder = new PolicyHolder(); //Dynamic objects will be stored in the heap.
    All objects are stored in the heap. There's no distinction between "dynamic" and "static."
    Class/static variables---Static variables are created when the program starts and destroyed when the program stops.Wrong. They are created when the class is loaded and destroyed when it is unloaded.
    I don't know where you got all this information from, but I recommend you don't use that site. Much of it is just plain wrong, and the rest is very poorly written and imprecise.

  • Is thread still active after main method exits?

    Hi All,
    Yesterday we were discussing. wether it is possible for a thread to be active even after the main method, from which it was spawned, exits.
    any comments?

    Hello,
    If you start a thread from the main() method and then return from main(), the thread will remain running. Just try it out:
    public class Test
        implements Runnable
        public static void main(String[] args)
            Thread t = new Thread(new Test());
            t.start();
            System.out.println("Returning from main()");
        public void run()
            try
                Thread.sleep(5000);     // Wait for 5 seconds
                System.out.println("Hello, I'm still here!");
            catch (InterruptedException ie)
                ie.printStackTrace();
    }Note: If you exit main() using System.exit(), all threads will be killed!
    Jesper

  • Question of the day: In which Thread context does the main method run ?

    let's say, you create a JFrame in the main method:
    public static void main(String[] args)
    new MyJFrame();
    let's suppose, you construct the whole JFrame
    inside the constructor, which contains a lot
    of other Swing components, like JTree's and more.
    AND the JFrame calls setVisible(true) in its
    constructor.
    -> According to my knowledge, this won't work
    properly - it will function, BUT you will get one
    or two quite big exceptions (which usually start
    with a nullpointer exception, produced by the
    PLAF, but the whole stacktrace shows, that the
    the exception was thrown AND catched inside
    the Swing objects.
    Reason for this would be, that all operations
    after the "setVisible(true)" statement must be
    carried out in the eventdispatch thread, according
    to Swing rules.
    Now, as you can see by running the source below,
    the main() method always is processed in special thread,
    NOT the event dispatch thread - which produces the above behaviour.
    My Question:
    Wouldn't it have been easier to let the JVM
    process the main() methods right in the
    event dispatch thread ?
    Or:
    Why is the JVM designed to process the
    main() method in a special thread and not
    the Swing event dispatch thread ?
    opinions?
    Regards
    JPlaz / SnowRaver
    package Test1;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame1 extends JFrame
    public Frame1( final String title, int position )
    this.setSize(400,300);
    this.setLocation(position,position);
    this.setVisible(true);
    if( SwingUtilities.isEventDispatchThread() )
    System.out.println("Constructor of "+title+" is processed IN the event dispatch thread.");
    else
    System.out.println("Constructor of "+title+" is processed in ANOTHER than the event dispatch thread.");
    public static void main(String[] args)
    // First creation just from the startup thread context :
    new Frame1("first Frame", 60);
    // Now we let the second creation be done in the
    // eventdispatch thread context for sure :
    SwingUtilities.invokeLater( new Runnable()
    public void run()
    new Frame1("second Frame",120);

    Matt,
    it's been so long, I don't have the full answer in my head.
    This page on Adobe.com has an example that shows Flash 4
    mouse stuff (I'm Mr
    Vague today) when you scroll down. Your timelinme reference
    will be
    something like
    TellTarget(_Root, gotoAndPlay(50))
    Hopefully from that vagueness you can locate the right
    answer.
    Steve
    Adobe Community Expert: Authorware, Flash Mobile and Devices
    My blog -
    http://stevehoward.blogspot.com/
    Authorware tips -
    http://www.tomorrows-key.com

  • Bouncing Ball without Main Method

    Hi. I needed to reserch on the Internet sample code for a blue bouncing ball which I did below. However, I try coding a main class to start the GUI applet and it's not working. How can I create the appropriate class that would contain the main method to start this particular application which the author did not provide? The actual applet works great and matches the objective of my research (http://www.terrence.com/java/ball.html). The DefaultCloseOperation issues an error so that's why is shown as remarks // below. Then the code in the Ball.java class issues some warning about components being deprecated as shown below. Thank you for your comments and suggestions.
    Compiling 2 source files to C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\build\classes
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:32: warning: [deprecation] size() in java.awt.Component has been deprecated
        size = this.size();
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:93: warning: [deprecation] mouseDown(java.awt.Event,int,int) in java.awt.Component has been deprecated
      public boolean mouseDown(Event e, int x, int y) {
    2 warnings
    import javax.swing.*;
    public class BallMain {
    * @param args the command line arguments
    public static void main(String[] args) {
    Ball ball = new Ball();
    //ball.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    ball.setSize( 500, 175 ); // set frame size
    ball.setVisible( true ); // display frame
    import java.awt.*;*
    *import java.applet.*;
    import java.util.Vector;
    // Java Bouncing Ball
    // Terrence Ma
    // Modified from Java Examples in a Nutshell
    public class Ball extends Applet implements Runnable {
    int x = 150, y = 100, r=50; // Position and radius of the circle
    int dx = 8, dy = 5; // Trajectory of circle
    Dimension size; // The size of the applet
    Image buffer; // The off-screen image for double-buffering
    Graphics bufferGraphics; // A Graphics object for the buffer
    Thread animator; // Thread that performs the animation
    boolean please_stop; // A flag asking animation thread to stop
    /** Set up an off-screen Image for double-buffering */
    public void init() {
    size = this.size();
    buffer = this.createImage(size.width, size.height);
    bufferGraphics = buffer.getGraphics();
    /** Draw the circle at its current position, using double-buffering */
    public void paint(Graphics g) {
    // Draw into the off-screen buffer.
    // Note, we could do even better clipping by setting the clip rectangle
    // of bufferGraphics to be the same as that of g.
    // In Java 1.1: bufferGraphics.setClip(g.getClip());
    bufferGraphics.setColor(Color.white);
    bufferGraphics.fillRect(0, 0, size.width, size.height); // clear the buffer
    bufferGraphics.setColor(Color.blue);
    bufferGraphics.fillOval(x-r, y-r, r*2, r*2); // draw the circle
    // Then copy the off-screen buffer onto the screen
    g.drawImage(buffer, 0, 0, this);
    /** Don't clear the screen; just call paint() immediately
    * It is important to override this method like this for double-buffering */
    public void update(Graphics g) { paint(g); }
    /** The body of the animation thread */
    public void run() {
    while(!please_stop) {
    // Bounce the circle if we've hit an edge.
    if ((x - r + dx < 0) || (x + r + dx > size.width)) dx = -dx;
    if ((y - r + dy < 0) || (y + r + dy > size.height)) dy = -dy;
    // Move the circle.
    x += dx; y += dy;
    // Ask the browser to call our paint() method to redraw the circle
    // at its new position. Tell repaint what portion of the applet needs
    // be redrawn: the rectangle containing the old circle and the
    // the rectangle containing the new circle. These two redraw requests
    // will be merged into a single call to paint()
    repaint(x-r-dx, y-r-dy, 2*r, 2*r); // repaint old position of circle
    repaint(x-r, y-r, 2*r, 2*r); // repaint new position of circle
    // Now pause 50 milliseconds before drawing the circle again.
    try { Thread.sleep(50); } catch (InterruptedException e) { ; }
    animator = null;
    /** Start the animation thread */
    public void start() {
    if (animator == null) {
    please_stop = false;
    animator = new Thread(this);
    animator.start();
    /** Stop the animation thread */
    public void stop() { please_stop = true; }
    /** Allow the user to start and stop the animation by clicking */
    public boolean mouseDown(Event e, int x, int y) {
    if (animator != null) please_stop = true; // if running request a stop
    else start(); // otherwise start it.
    return true;
    }

    FRiveraJr wrote:
    I believe that I stated that this not my code and it was code that I researched.and why the hll should this matter at all? If you want help here from volunteers, your code or not, don't you think that you should take the effort to format it properly?

  • Static main methods and run()

    I am having trouble with main methods, and how to structure code, im not 100% sure on what static methods are, and im not sure how to use it when calling other methods etc cos its static and stuff - i read that i should put stuff in the constructor - but im not sure how this will work with a run()
    I have written a program to draw some objects (just an oval at a certain position)
    anyway here is the main method:
    public static void main(String[] args) {
            // TODO code application logic here
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Main game = new Main();
                    game.createAndShowGUI();
                    //Create some graphics objects at the desired position!
                    GOA[0] = new GraphicsObject(300,200);         *
                    GOA[1] = new GraphicsObject(350,200);         *
                    game.frame.updateGraphics(GOA);            *
        }I am getting "non-static variable GOA cannot be referenced from a static context" at * i cant just make everything static, how should this be structured? where should the run() be?
    Thanks for any help

    Ok, i might as well include the whole thing - its not too big , and i would like to see if any of it is right really.
    ackage joefootball2;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferStrategy;
    public class Main {
        GameWindow frame;
        //Create the graphics object array to pass to the painting stuff
        GraphicsObject[] GOA;
        private void createAndShowGUI() {
            //Create and set up the window.
            frame = new GameWindow();
            frame.DrawWindow();
        public static void main(String[] args) {
            // TODO code application logic here
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Main game = new Main();
                    game.createAndShowGUI();
                    //Create some graphics objects!
                    GOA[0] = new GraphicsObject(300,200);
                    GOA[1] = new GraphicsObject(350,200);
                    game.frame.updateGraphics(GOA);
    class GameWindow extends JFrame
        DrawPanel canvas;
        public void updateGraphics(GraphicsObject[] GOA)
            canvas.updateObjects(GOA);
        public void DrawWindow()
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            canvas = new DrawPanel();
            canvas.setDoubleBuffered(true);
            this.getContentPane().add(canvas);
            this.setVisible(true);
            this.setSize(800, 600);
            this.setResizable(false);
    class DrawPanel extends JPanel
        //Create the graphics object array to draw
        GraphicsObject[] GOA;
        public void updateObjects(GraphicsObject[] givenGOA)
            GOA=givenGOA;
        public void paint(Graphics g)
            for (int i=0 ; i<GOA.length ; i++)
                g.drawOval(GOA.x-5, GOA[i].x-5, 10, 10);
    class GraphicsObject
    //for now, just make the graphics object a point to draw a circle
    int x; int y;
    }thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Triggering method after loading of gui

    hi there.
    I have a single frame java application that connects to a mysql instance for data storage.
    What I would like is to trigger a method after the gui loads.
    How can this be accomplished?
    Cheers

    Just do what all the IDEs generate code to do: invoke SwingUtilities.invokeLater() after creating all the GUI objects.

  • Does main method have to be static? Is there a way to go around it?

    I am trying to write a class that will recursively walk through directory listing of a given ftp adress and store it in a text file in this format:
    <path> , DIR // if directory
    <path> , file // if file
    Since I am not yet experienced to do my own socket programming(tried and did not work out) I used Secure iNet Factory's library. And since I will be running multiple instances of this class I concluded that my fields and methods should not be static. Here is the class I wrote:
    import com.jscape.inet.ftp.Ftp;
    import com.jscape.inet.ftp.FtpException;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.net.URL;
    import java.util.Enumeration;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    public class test {
         private String path = "/";
         private String name;
         private String adres;
         // create new Ftp instance and connect.
         public test(String Name, String Adres) throws IOException {
              name = Name;
              adres = Adres;
              System.out.println("Test class: " + name);
              try {
                   Ftp ftp = new Ftp(adres,"anonymous","anonymous");
                   ftp.connect();
                   Enumeration e = ftp.getDirListing();
                   iterate(path, ftp);
                   ftp.disconnect();
              catch (FtpException ex) {
                   Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
         void iterate(String aStartingDir, Ftp ftp) throws FtpException, IOException {
              //Set the path.
              path = path + aStartingDir + "/";
              // Change directory.
              ftp.setDir(aStartingDir);
              // Iterate through directory list.
              Enumeration e = ftp.getDirListing();
              while(e.hasMoreElements()){
                   Object f = e.nextElement();
                   // Recursive call if item is directory.
                   if(f.toString().startsWith("drwxrwxrwx") &&
                        // Ignore "." and ".."
                        !f.toString().substring(55).trim().equalsIgnoreCase(".") &&
                        !f.toString().substring(55).trim().equalsIgnoreCase("..")) {
                        // Write to index file.
                        URL dirUrl = FtpCheck.class.getResource("./index/"); // get the directory.
                        URL fileUrl = new URL(dirUrl, name + ".txt"); // construct the file path.
                        String filePath = fileUrl.getPath().replaceAll("%20", " "); // fix spaces.
                        BufferedWriter file = new BufferedWriter(new FileWriter(filePath,true));
                        file.write((path + f.toString().substring(55).trim()).substring(3)
                             + ",DIR\n");
                        file.close();
                        iterate(f.toString().substring(55).trim(),ftp);
                   // Skip entries "." and ".."
                   else if (f.toString().substring(55).trim().equalsIgnoreCase(".") ||
                             f.toString().substring(55).trim().equalsIgnoreCase("..")) {
                             continue;
                   // Add files to the index.
                   else {
                        URL dirUrl = FtpCheck.class.getResource("./index/"); // get the directory.
                        URL fileUrl = new URL(dirUrl, "index.txt"); // construct the file path.
                        String filePath = fileUrl.getPath().replaceAll("%20", " "); // fix spaces.
                        BufferedWriter file = new BufferedWriter(new FileWriter(filePath,true));
                        file.write((path + f.toString().substring(55).trim()).substring(3)
                             + ",file\n");
                        file.close();
              // End of listing reached, go one directory up.
              ftp.setDirUp();
              // And remove the last directory name from path.
              path = path.substring(0,path.lastIndexOf("/"));
              path = path.substring(0,path.lastIndexOf("/")) + "/";
    }which compiles fine.
    Here is the class that invokes it:
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author Sentinel
    public class NewClass {
         public NewClass() {
         public static void main(String args[]) throws MalformedURLException, FileNotFoundException, IOException {
              index t = new index("El Naga","elnaga.sytes.net");
              t.start();
              index t1 = new index("Afacan","afacan.myftp.org");
              t1.start();
         public class index extends Thread {
              String name;
              String adres;
            public index(String Name,String Adres) {
                name = Name;
                adres = Adres;
            @Override
            public void run() {
                try {
                    test checker = new test(name,adres);
                catch (IOException ex) {
                     Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }when I hit run build fails:
    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\Sentinel\My Documents\NetBeansProjects\ftpCheck\build\classes
    C:\Documents and Settings\Sentinel\My Documents\NetBeansProjects\ftpCheck\src\NewClass.java:19: non-static variable this cannot be referenced from a static context
                    index t = new index("El Naga","elnaga.sytes.net");
                              ^
    C:\Documents and Settings\Sentinel\My Documents\NetBeansProjects\ftpCheck\src\NewClass.java:20: non-static variable this cannot be referenced from a static context
                    index t1 = new index("Afacan","afacan.myftp.org");
                               ^
    2 errors
    BUILD FAILED (total time: 0 seconds)I (now)know that main method has to be static. I'm stuck and in need of help to overcome this obstacle. Is there a way to do this?

    a stab in the dark, but what if you make index a non-internal class. make it a stand-alone class in it's own file. Either that or make it a static inner class (almost the same thing).
    Your problem is that an inner class needs an instance of the outer class to start on, and you're not doing this. Another solution would be to do this kludge:
    index t = new NewClass().new index("El Naga","elnaga.sytes.net");  // I think this is how to call itBut again better is to make index a stand-alone class.
    Edited by: Encephalopathic on Oct 28, 2008 8:06 AM

  • How to increase the Java Heap Space for a main method

    Hello all,
    after a given number of calculations inside a class with main-method, I get an OutOfMemoryError (Java Heap Size).
    So I'm just trying to increase the Heap Size Creator uses, but it won't work.
    After reading a lot of posts and online-articles, I tried the following:
    1) I changed the -Xms and -Xmx options (to 512m) both in
    $CREATOR/SunAppServer8/domains/creator/config/domain.xml and
    $CREATOR/etc/creator.conf (this file also points to the Creator built-in JDK)
    2) additionally I tried to start Creator from the console with the respective option:
    ./creator -J-Xmx512m
    The memory toolbar shows the right value, but when I use
    System.out.println("JVM maximum memory:\t"+Runtime.getRuntime().maxMemory()/1024+" KB\n");it always says 64 MB, no matter which option I chose in the config-files.
    So how can I increase this value?
    Regards,
    Felix
    Message was edited by:
    Felice
    Message was edited by:
    Felice

    Thank you very much,
    this was an important hint. Additionally I had to create a new "Java Class Library" project with a copy of the needed files (those that are not dependent on the Application Server). Then I could use the option you mentioned.
    Unfortunately, when I try to run the file with
    java -jar FILENAME.jarit won't work, because the archive is not complete: MANIFEST.MF lacks the main-class and all involved libraries.
    I managed to add the main-class attribute manually, but adding all library references seems to be very error-prone.
    So does anyone know if I did something wrong or if this is a bug of Creator?
    Regards,
    Felix

  • Adding a class to a project in sunone studio that already has a main method

    i have a frame class and it contains a main method, I can't figure out how to add a class that makes use of the JDialog and call it from the main class. When i try to add a JDialog, it creates its own main method.
    If abc.class is my main method class and dcf.class is my class that makes the dialog GUI, I want abc.class to be able to call it, i can't figure out how to do this in Sun One Studio 5

    Having a main() in the JDialog doesn't hurt. It lets you run the JDialog as a standalone - make sure that it looks good, etc. When you run your other class, the main() won't get called. (And you can delete it when you're all debugged.
    Alternatively, create a new class, then start it by saying
    class MyDialog extends JDialog {
    }S1S will be completely happy if you do it that way.

Maybe you are looking for

  • I have an Ipod touch and cannot take it off headphone mode, Can anyone help please.

    I have an Ipod touch and cannot take it off headphone mode, Can anyone help please. Thankyou

  • How to determine which FileChooser ExtensionFilter has been selected

    Hi, I'm using a JavaFX fileChooser.showSaveDialog with two extension filters (*.csv and *.xml). How can I determine which filter was selected when the end-user clicks the save button? I am writing a program that allows the end-user to create an outpu

  • Instance stuck in OBPM 10GR3

    Hello all, We have a problem with one of our processes. There is an instance which is stuck in one of the Interactive activities waiting for someone to login and execute it. The person who was suppose to execute it has left the organization. Now we h

  • Doubt in assessment cycle

    Hi All, I have the following doubt in assessment cycle :- Consider the following scenario. There are three cost centres :- D015, D020 and D025 . An assessment cycle is being created where D015 is the sender  and D020, D025 are the receivers . A cost

  • FB3 Install Hangs at "Installing Merge Module"

    When i try to install Flex Builder 3 or Flex Builder 3 Plug-in the installer hangs at this dialog Installing... Install Merge Module(Build Time): FlashPlayerMergeMo... Installing Merge Module Anyone know how to fix this?