Dispose a JDialog Object

What is the correct procedures to dispose a JDialog Object for Garbage collection?
Let's say d is a JDialog Object Do I need to do all of the following 2 instructions or just one of them?
1......................d.dispose;
2......................d=null;

Could anyone help me?

Similar Messages

  • Disposing of an object

    hi,
    is there a way to dispose of an object, i'm having some problems with a jdialog, it's created when a jlabel is clicked in a jframe as:
         MouseListener labelListener = new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
                   LSNote1 noteOne = new LSNote1(SpotNoteFrame.this);
                   noteOne.setVisible(true);
         };The code for the class that extends jdialog is:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    class LSNote1 extends JDialog {
         public LSNote1(JFrame frame) {
              super(frame,"", true);
              JLabel label6 = new JLabel(new ImageIcon("tessst.jpg"));
              label6.setTransferHandler(new ImageSelection());   
              MouseListener mouseListener = new MouseAdapter() {     
                   public void mousePressed(MouseEvent e) {       
                   JComponent jc = (JComponent) e.getSource();       
                   TransferHandler th = jc.getTransferHandler();       
                   th.exportAsDrag(jc, e, TransferHandler.COPY);     
              addWindowListener(new WindowHandler());
              label6.addMouseListener(mouseListener);
              getContentPane().add(label6);
              setSize(150,150);
              //setUndecorated(true);
              //  Handler class for window events
         class WindowHandler extends WindowAdapter {
              //  Handler for window closing event
              public void windowClosing(WindowEvent e) {
                   dispose();                              //  Release the window resources
    }but everytime i click the jlabel to see the LSNote1 i see the same image (.gif) from before, it's not disposing of the object noteOne, i want it so that everytime LSNote1 is closed the object is distroyed so that next time the jlabel is clicked the latest image will be loaded.
    Thanks.

    Look at the source for ImageIcon.
    It makes a call to Toolkit.getDefaultToolkit().getImage(filename);
    The documantation for Toolkit.getDefaultToolkit().getImage(filename) reads:
    Returns an image which gets pixel data from the specified file,
    whose format can be either GIF, JPEG or PNG.
    The underlying toolkit attempts to resolve multiple requests with the same filename to the same returned Image.
    Since the mechanism required to facilitate this sharing of
    Image objects may continue to hold onto images that are no
    longer of use for an indefinite period of time, developers
    are encouraged to implement their own caching of images by
    using the createImage variant wherever available.
    I think that says it all.

  • How to load a background Image on a JDialog object

    Hi All, Actually i am new to java programing and i am stuck in this problem. I am developing a java application which is dialog based (using JDialog objects) and i want to load a background image on my dialog. I hope this could be done and i really appreciate your help because i must deliver this project and this is a user interface requirement.

    Try something along the lines of this: Create a new class called BackgroundImagePanel and have it extend JPanel.
    Have an attribute in the class for your image, and a method to set it.
    Override isOpaque() to return true.
    Override the paintComponenet method as such:
    public void paintComponent (Graphics g) {
    super.paintComponent(g);
    if( image == null ) return;
    Icon icon = new ImageIcon(image);
    icon.paintIcon(this, g, x, y);
    Add this panel to your JDialog and then add other component to this panel.
    You might have to tweak this a bit, but it should get you close...
    Bill

  • Automatically dispose a JDialog after a certain time

    HI all,
    To dispose a JDialog by a user response I've add a button event and dispose it. Say user not click the button within one minute after displayed it. In that case I want to automatically dispose it. How can I do it.
    Thanks
    ItsJava

    Yes, I'm working on Timer as you said. What I'm asking in that code is what I tried. :) I think most of you think it is not a good approach at all :)
    Here what I try with the timer.
        public void autoHide(final JDialog mainDialog){
            int counter = 0;
            Timer timer = new Timer(1, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(mainDialog.isVisible()){
                         // In each second try to increment the counter by one
                         // if the counter is equal to 5 dispose the dialog
            timer.start();
        }I stuck here, I can't change the variable counter int the timer. IDE inform that used constant values.

  • Windows\Temp folder filling fast - how to Dispose the Crystal Objects?

    Post Author: pontupo
    CA Forum: .NET
    So the Windows\Temp folder is fast filling the disk in my
    deployment. Each time a report is opened, a number of files are created
    here. The problem is, of course, probably that I'm not releasing my
    report objects in my code, as the reports can't even be manually
    deleted without shutting down IIS. Well, fair enough. What I can't
    figure out is where to release my reports objects. I have two pages:
    one performs a pre-pass of the report object and generates a dynamic
    page to prompt the user for parameters. This page, I believe, has no
    problems because the report.Close() command is in line with the code
    and is the final statement, but I could be mistaken and this page may also be leaving memory leaks. The second page, however, has the
    CrystalReportsViewer object and actually displays the report to the
    user after setting up the parameters correctly. On this page, I can't
    figure out how/when to call report.Close(). If I do it at the
    page.Dispose event, there seems to be no affect. If I do it at the
    page.Close event, the report will load fine, but if you try to go to
    another page in the report (in the case of multi-page reports) or
    refresh the data, the report object has already been unloaded and the
    CrystalReportsViewer won't be able to find the report document. If I
    wrap my code in one big Try-Catch-Finally (rather than just having a
    Try-Catch around the file load itself) as I've seen suggested elsewhere and place a report.Close()
    command in the Finally, the Finally is executed before the viewer even
    loads the report so I get a file not found error. So where
    can I unload the report object? What I want is to persist the report
    via Sessions (which I do) so that as the user moves between pages of
    the report/refreshes the report will remain loaded, but when the user
    closes the page or browses to another page, perhaps, I want to close
    the report and free the resources so that the temp files are deleted.
    Following are some code samples: Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init        sessionString = Request.QueryString("report")        report = Server.MapPath("reports/") & Request.QueryString("report") & ".rpt"        ConfigureCrystalReport()    End SubPrivate Sub ConfigureCrystalReport()        If (Session(sessionString) Is Nothing) Then            reportDoc = New ReportDocument()            'load the report document            If (IsReportValid()) Then              reportDoc.Load(report)              '******************************              'bunch of other code, authentication              'parameter handling, etc. here              '******************************              Session(sessionString) = reportDoc        Else                Response.Redirect("error.aspx")            End If        Else            reportDoc = CType(Session(sessionString), ReportDocument)        End If    CrystalReportsViewer.ReportSource = reportDoc    End Sub    Private Function IsReportValid() As Boolean        Dim reportIsValid As Boolean = False        Try            If (System.IO.File.Exists(report)) Then 'does the file exist?                'if it does, try to load it to confirm it's a valid crystal report                Dim tryReportLoad As New CrystalDecisions.CrystalReports.Engine.ReportDocument()                tryReportLoad.Load(report)                tryReportLoad.Close()                tryReportLoad.Dispose()                reportIsValid = True            End If        Catch ex As Exception            reportIsValid = False        End Try        Return reportIsValid    End Function'Currently, I've also tried each of the following:Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload        CloseReports(reportDoc)        CrystalReportsViewer.Dispose()        CrystalReportsViewer = Nothing    End Sub    Private Sub CloseReports(ByVal report As ReportDocument)        Dim sections As Sections = report.ReportDefinition.Sections        For Each section As Section In sections            Dim reportObjects As ReportObjects = section.ReportObjects            For Each reportObject As ReportObject In reportObjects                If (reportObject.Kind = ReportObjectKind.SubreportObject) Then                    Dim subreportObject As SubreportObject = CType(reportObject, SubreportObject)                    Dim subReportDoc As ReportDocument = subreportObject.OpenSubreport(subreportObject.SubreportName)                    subReportDoc.Close()                End If            Next        Next        report.Close()    End Sub'This was the solution suggested on another forum. I've also tried:Protected Sub Page_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed        reportDoc.Close()        reportDoc.Dispose()        CType(Session(sessionString), ReportDocument).Close()        Session(sessionString) = Nothing    End Sub'I've also tried wrapping everything inside of the If statement in the ConfigureCrystalReport() method in code to this effect:If (IsReportValid()) Then                Try                    reportDoc.Load(report)Catch e As Exception                    Response.Redirect("error.aspx")                Finally                    reportDoc.Close()                End TryAny advice on this is appreciated. Thanks in advance, Pont

    Post Author: sarasew13
    CA Forum: .NET
    Why are you checking for is valid before closing?  As long as the report object isn't null you should be able to close it (whether it's open or not).  I ran into this same problem when trying to store the report, so now I just store the dataset.  Everything seems to work fine and navigate appropriately so here's more or less how I handle it:
    DataSet myDS;ReportDocument myRPT;
        protected void Page_Load(object sender, EventArgs e)    {        try        {            if (!IsPostBack)            {                //pull variables from previous page if available                //set variables into view state so they'll persist in post backs            }            else            {                //if postback then pull from view state            }
                createReport();    }        catch (Exception err)        {            //handle error        }    }
        private void createReport()    {        myDS = new DataSet();        string rpt;
            rpt = "RPTS/report.rpt";        try        {            if (!IsPostBack || Session["data"] == null)            {                myDS = getData();//make data call here                Session["data"] = myDS;            }            else            {                myDS = (DataSet)Session["data"];            }
                if (myDS.Tables.Count > 0)//make sure the dataset isn't empty            {                myRPT = new ReportDocument();                myRPT.Load(Server.MapPath(rpt));                myRPT.SetDataSource(myDS.Tables[0]);
                    if (!IsPostBack)                {                    //code to set parameters for report here                }
                    MyViewer.ReportSource = myRPT;            }        }        catch (Exception error)        {            //handle error        }    }
        protected void Page_Unload(object Sender, EventArgs e)    {        try        {            if (myRPT != null)            {                myRPT.Close();            }        }        catch (Exception error)        {            //handle error        }    }

  • Hi..everybody...problem in dispose of JDialog

    I am opening JDialog for showing some information in JApplet. When user disposes (Pressing Ok button) JDialog, JApplet looses focus and user is unable to stir through JApplet with the help of hotkeys.
    Please help me to solve this problem

    u can add a windowlistener to the dialog
    addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
    code to focus the applet
    })

  • Question about JDialog - dispose()

    I use in my application a custom JDialog to get inputs from the user.
    When the "ok" button is pressed, i store all the inputs i need inside an object and then i dispose the JDialog.
    Now, the code which made the JDialog retrieve the object containing all the inputs through a call to a method of my custom JDialog.
    But this happens after i called dispose() on my JDialog.
    According to what i understood about it, it should release all the resources related to the JDialog and all its own children, so, how can i possibly access to it after i have disposed it?
    The object is not destroyed?
    Is there a time interval before it is "destroyed"?
    Thanks,
    Nite

    According to what i understood about it, it should release all the resources related to the JDialog and all its own children, so, how can i possibly access to it after i have disposed it?Read more carefully.
    Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.
    dispose() doesn't pre-empt the garbage collector. The native resources related to displaying the dialog are released, not the associated Java objects.
    Fresh resources will be obtained form the OS if the dialog is redisplayed.
    The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show.
    db

  • How can I tell if a Graphics object has been disposed

    Any ideas?
    Thanks

    My goal is to find out if a graphics object has been disposed or not...
    ...but I'll play along. the application offers the user some nice graphics to amuse them, I use the Graphics object. In my endeavours, something isn't getting displayed where I expect it to, and I suspect that somewhere I'm accidentally disposing the graphics object. So, like checking for nulls, I want to debug the application and make sure the graphics context is as I expect.
    A bit of a side note, SWT will throw an exception if you try and use a "graphics" type object that has been disposed and has a method called, unsurprisingly enough, isDisposed(). Can you guess what it returns?

  • Webpart objects should be disposed ?

    Hi,
    I am looping through the webparts in a page using webpartmanager as shown below. Should i dispose web part objects.(inside for loop)
    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wpManager.WebParts)

    In general, if there is a Dispose method, and you created the object, then you should call Dispose. But before you do, visit this page and search for "WebParts":
    https://msdn.microsoft.com/en-us/library/office/ee557362(v=office.14).aspx  There they say to Dispose the SPLimitedWebPartManager, but I don't see System.Web.UI.WebControls.WebParts.WebPart listed there.
    I would probably call it, especially if there are there any custom web parts.
    Mike Smith TechTrainingNotes.blogspot.com
    Books:
    SharePoint 2007 2010 Customization for the Site Owner,
    SharePoint 2010 Security for the Site Owner

  • Tranfer data from a jdialog to a frame!

    Hello, everybody?!That is my doubt!!There's a jtable inside a jdialog, when a row was selected, and the "enter" key was pressed, i'd like to send the data to a frame (main).How could i create that?Thanks!!

    here's something rough - just sets the selection as the label's text. modify for the row data
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    class Testing
      JLabel selection = new JLabel("Selected Value = ");
      public void buildGUI()
        JButton btn = new JButton("Get Selection");
        final JFrame f = new JFrame();
        f.getContentPane().add(selection,BorderLayout.NORTH);
        f.getContentPane().add(btn,BorderLayout.SOUTH);
        f.setSize(200,80);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            final JDialog d = new JDialog();
            Object[] cols = {"A","B","C"};
            Object[][] data = {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};
            final JTable table = new JTable(data,cols){
              public boolean isCellEditable(int row, int col){
                return false;
            JScrollPane sp = new JScrollPane(table);
            sp.setPreferredSize(new Dimension(100,100));
            d.setModal(true);
            d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
            d.getContentPane().add(sp);
            d.pack();
            d.setLocationRelativeTo(f);
            Action enterAction = new AbstractAction(){
              public void actionPerformed(ActionEvent ae){
                selection.setText("Selected Value = " +
                table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()));
                d.dispose();
            InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
            KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
            im.put(enter, "enter");
            table.getActionMap().put(im.get(enter), enterAction);
            d.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Redispaying a window after calling dispose() in MacOS

    When I call dispose() on an object that extends JDialog and then later call
    pack();
    setVisible(true);
    on the same object, the window reappears as it should except in MacOS.
    When im running the program in MacOS, the redisplayed window isn't quite the same.
    Selected checkboxes, the right end of comboboxes, the borders of clicked buttons,
    aren't highlighted (either blue or graphite).
    Is there any way to get around this?

    Read the API.
    Yes but it also says that calling show or pack after dispose should
    re-create the native resources exactly as they were before Oops... talk about tunnel vision. Even without reading that, I should have known that it was possible since I knew that components don't get "realized" until a pack or show is done.

  • How to find JDialog(s) that have JFrame owner

    I have an application with a single JFrame container, holding a JPanel which represents one functional component in the app suite. When I get a RuntimeException, I want to close the current JPanel and return the application to a login prompt. That much I can handle.
    I call frame.removeAll() to remove all the components in the frame. However, in a situation where a dialog is displayed, which may in turn launch another dialog, removeAll() does not dismiss or dispose any JDialogs which have this frame as the owner, or are descendants of this frame..
    Is there a way to do this? Also, (of course) the second -nth dialog would have the n-1 dialog as its owner.
    I thought of finding the focus, getting its parent that is a JDialog, and calling dispose, until I get to the JFrame. However, SwingUtilities.findFocusOwner(frame) returns null on the 1st call.

    Calling frame.removeAll() only removes the components contained within it, which in this case are the components that were added to its rootpane. It will not dispose of your dialogs, even if the frame is the "parent" to those dialogs. This is because those dialogs only contain a reference to the parent (frame, in this case), but the frame itself doesn't know that those dialogs are holding references to it.
    The solution here is to explicitly dispose of those dialogs next to the code where you call frame.removeAll(), meaning that you should also keep references to those dialog objects so that you can make calls to dispose of them.
    Or, if you want a custom removeAll() method on frame to dispose of those dialogs, then make an object which: 1) extends from JFrame, 2) holds references to those dialogs, and 3) overrides the removeAll() method to call super.removeAll() and then makes calls to dispose of those dialogs.

  • Disposing RefCursor does not close RefCursor?

    Hi,
    I want to dispose the OracleRefCursor after executing the executedatatable command. To achieve this, i tried to dispose the OracleRefCursor object but it did not close the cursor, i saw the related cursor in v$open_cursor table. So how can i close the opened cursor without closing the connection or committing or rollback? Thanks...
    The code that i tried to close cursor is:
    OracleParameter m_Cursor = m_Command.Parameters["pCursor"];
    m_Cursor.Dispose();
    It did not work.

    Hi,
    According to AskTom the fact that you see it in v$open_cursor doesnt mean it's necessarily open.
    Are you seeing a problem as far as ORA-1000 that you're trying to troubleshoot for example? Or is this just something you noticed?
    Thanks
    Greg

  • Closing or Disposing the Connection Does Not Release Open Cursors

    Hi,
    I have an architecture like this:
    Web Service ---> Business COM+ Component ---> Data COM+ Component
    I found that doing a SetAbort() plus explicitly close and dispose the OracleConnection object in my COM+ component does not necessarily close the open cursor.
    The way I tested was I would call the same same service multiple times and do a "select * from v$open_cursor where user_name = 'xxx'", I would see a bunch of open cursors with exactly the same SQL_TEXT. The only way to close those open cursors seems to be killing the aspnet_wp.exe process in the Task Manager.
    Someone here suggested it might be .NET's problem but I don't think so since I had the same problem with OraMTS 9i.
    Can someone from Oracle help? Thanks.
    -Linus

    Neeraj,
    Thank you for your reply. I'd like to let you know that my company submitted a TSR ticket last year (around Oct.?) on this issue and it's still not fixed, yet. This problem prevents us from using COM+ to handle any transactions, which is not acceptable to us. Please try to raise the issue again to your development team if you can, we are depending on the fix.

  • Color of a JDialog

    I want to set the background color of a JDialog. I used the follwing code but it doesn't work:
    Object[] options = {"Oui","Non"};
              JOptionPane optionViderChamps = new JOptionPane(
                   "�tes-vous certain de vouloir vider les champs ?",
                   JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_OPTION,
                   null,options,options[0]);
              optionViderChamps.setBackground(Color.white);
              JDialog dialogViderChamps = optionViderChamps.createDialog
                   (framePrincipal, "VIDER LES CHAMPS");
              dialogViderChamps.getContentPane().setBackground(Color.white);
              dialogViderChamps.show();

    Hi,
    remove that getContentPane() and call setBackGround(Color.white) directly on the JDialog object.
    It should work.
    durga

Maybe you are looking for

  • Deleted songs on ipod and computer

    somehow all the songs got deleted off my ipod...when i tried to upload them back on it says my ipod cannot be uploaded because the playlists no longer exist!!! how do i get my playlist back so i can have songs agian????

  • Function module to Create payment lot name

    Hi ,      I have to create a new payment lot from a Z program (program will run in a batch mode) and this payment lot will be passed to standard bapi : BAPI_CTRACPAYMINC_APPEND to upload the data in payment lot. For creation of payment lot I am using

  • Can i use old and new version of iPhoto on one computer with 2 users

    my partner wants to use the new version with his library and i want to stick with the old iPhoto 6 for now. i haven't opened iPhoto 8 on my side yet and when i look for the old version of iPhoto 6 i don't see it... i thought it was supposed to remain

  • Data size discrepancy

    I've been doing some compression tests for a clip destined for the web. I noticed when looking at the finished versions that the file sizes shown in the Movie Info box in QT Pro are different from those shown in the finder. For one file QT Pro shows

  • Renumbering table containing high numeric values

    Hi guys, I have a table containing millions of records but there's a numeric gap in the auto-generated id's for the ID column (primary key). I want to ALIGN the numbering for this table so that it doesn't jump from 7 to 100000008... but instead conti