e.getWindow().dispose() is not working? - swing

I have a main program which calls a JFrame to get User information, If a user press submit I am storing the information in POJO and getting it into Main program.
If User clicks on Exit, I want to dispose the JFrame and want to exit the main program as well after executing one logging statement in main method.
If I use -
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
and
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
e.getWindow().dispose();
}
});
all the Threads exit immediately and I am not able to execute logging statments in main method.
If I use-
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
e.getWindow().dispose();
}
});
My main method execute those logging statments but it never exit, It stay silent after executing all the statements.
If I use this -
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
Thread.currentThread.interrupt();
}
});
Everything works fine. But is it the correct way of doing this?

In theory, if you dispose all top-level windows, the JVM should terminate cleanly.
However, there are a few details to make sure, which are detailed on this page:
Therefore, a stand-alone AWT
application that wishes to exit
cleanly without calling System.exit
must:
Make sure that all AWT or Swing components are made undisplayable when
the application finishes. This can be
done by calling Window.dispose on all
top-level Windows. See
Frame.getFrames.
Make sure that no method of AWT event listeners registered by the
application with any AWT or Swing
component can run into an infinite
loop or hang indefinitely. For
example, an AWT listener method
triggered by some AWT event can post a
new AWT event of the same type to the
EventQueue. The argument is that
methods of AWT event listeners are
typically executed on helper threads.
If you don't manage to find what keeps the program alive, there can be another way:
-Use the first method you described, with the EXIT_ON_CLOSE
-Add a ShutdownHook to the runtime, to execute your last logging statements:
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
//logging statements
});

Dispose method only releases system resources.
To actually close the window you have to call setVisible(false)

Related

Run code on periodic timer after services registered

I have a class which I'd like to run a method on periodically. I'd prefer to do this with a timer method, so built the class with a method: StartPolling() which would then call my DoSomething() method every 60 seconds.
I tried to start the polling from the Main method in Program.cs:
public static void Main(string[] args)
{
var webHost = BuildWebHost(args);
ConfigureApp();
var cam = IocManager.Instance.Resolve<CameraManager>();
webHost.Run();
}
But when I try resolve an instance (CamerManager) I get an error that other things that CameraManager depends on haven't been registered, e.g. repositories.
What's the best way to do this...and I do not want to use the ABP background jobs as ASP.NET may "go to sleep" so my tasks wouldn't get run on time.
Thanks
Chris

How to create a custom events in C#

I'm trying to develop an application using C# wiforms. I want to execute void sendEmail(){} function in a class only when internet connection is up. The method that I used is bool checkConnection(){} function infinitely loops a while loop and sending ping requests to google.com. if the ping is successful, sendEmail(){} function is called by the checkConnection() function.
But i know this is not the best practice of doing this. I'm very confusing about custom events in C#. how to use custom events to accomplish this task. expecting an answer with simple explanation.
Thanks in advance
I understand that you are trying to build a scheduler task like functionality in c#. Based on my understanding, a windows service would do the task for you like listening for the availability of internet and then performing the mail sending operation when the application goes online.
W.R.To Events, you can build your own event engine that the one that raises the application events when the app runs and then there will be database entries that lists the pending tasks. There will be a background job like a windows service that reads the database and based on the availability of internet or on some condition executes the job.
If you can be more clear on the exact use-case and what you have tried so far the community can help you better.
Sample
class Observable
{
public event ImageUploadeventHandler InternetcOnnected;
public void DoSomething()
{
ImageUploadeventHandler handler = InternetcOnnected;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
class Observer
{
public void HandleEvent(object sender, EventArgs args)
{
// upload the image to the online service
}
}

Exit app and constructor no longer called on Windows Phone 8

I have a constructor with data to be loaded when the Application run for the first time. However when I press back to exit my application, I can no longer load the constructor once I launch the application again. However this problem will not exist when I press the window button and proceed to select my application. The constructor data will still be loaded for this scenario:
public MainPage()
{
InitializeComponent();
loadData();
}
It is because some information is saved in the memory.
So if you want to call it everytime you login subscribe to the loaded event.
So in your construvtor write this.loaded += and what you want this will allways be called.

WinRt: Suspend and Resume - when should I release my resources and allocate it again?

My WinRt app implements a simple HttpServer. That server gets started when the app starts and should be terminated when the app ends. The HttpServer receives some callbacks from an other remote third party component. I need to register und unregister my HttpServer at the third party component.
My problem here is the Application lifecycle of an WinRt App especially the situation suspend -> resume (without Terminated or ClosedByUser).
In that situation the "OnSuspending" method is called while suspending, but nothing gets called when resuming.
In my App I unregister the HttpServer from the third party component during "OnSuspending".
The question is what gets called so I can reregister my HttppServer at the third party?
Any help is much appreciated!
There is a Resume event, define it in your App.xaml.cs constructor
public App()
{
InitializeComponent();
Suspending += OnSuspending;
this.Resuming += On_resuming;
}
And write your Resume event
private async void On_resuming(object sender, object e)
{
}
Hope it helps

How to perform repetitive actions in PureMVC flex application?

Currently working on a flex AIR project based on PureMVC framework. There was a new requirement to the project, an operation is to be performed repetitively at regular interval which has some business logic. As per PureMVC this should be placed in the command, but then command would get garbage collected the moment its executed.
Given the scenario there are few doubts/confusions/clarifications...
Creating a command with business logic would be one solution ... but then who would trigger it at specific interval? (shouldn't this be done by a command as per PureMVC)
Placing the command trigger in a mediator or placing the logic in a mediator (this would make pureMVC a bit impure :) )
How do I find a solution for this kind of scenario?
You need to pull apart the async process you want to run and the repetitive triggering of said process. My advice is to create a Proxy for the async process and a separate Proxy that's a wrapper for a Timer which simply sends a notification upon timeout. The notification is coupled to a command, which in turn calls the async proxy's methods. That way you can add logic to the command for instance what to do if the process is still busy.
The benefits of creating two proxies: you adhere to SRP. You can easily swap/modify/remove the timing proxy w/o touching the async proxy. Everything is nicely separated.
depends on what the Command should do - if it updates the Model put a Timer in one of your Proxy class and send a Notification every xx seconds which is mapped to a Command that does whatever it is you want it to do.
If it should just update the View you could add the Timer to the corresponding Mediator but then you wouldn't need a Command at all.
**
Don't create more Singletons than you need. ApplicationFacade is already one - try and keep it that way.
**
If you have to do any async calls to the backend, just make sure to add the EventListener without weakReference set to true - then everything should be ok...
Try this:
Create a Singleton class - singleton class in Flex
Have a function in this class (eg. called start) that when called starts a timer, the callback function of which sends a notification, that triggers a command that does your business logic.
When you are ready to start your regular actions simply call the get instance method on your singleton, to create the singleton and then call it's start() function.
*Optionally have a stop function that cancels the timer and stops the regular notifications being sent.
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
public final class RepititiveSingleton
{
private var timer:Timer;
private static var instance:RepititiveSingleton= new RepititiveSingleton();
public function RepititiveSingleton() {
if( RepititiveSingleton.instance ) {
throw new Error(
"ReptitiveSingleton can only be accessed through Singleton.getInstance()" );
}
}
public static function getInstance():RepititiveSingleton{
return RepititiveSingleton.instance;
}
public function start(interval:Number = 1000):void {
timer = new Timer(interval);
timer.addEventListener(TimerEvent.TIMER, onTimer);
}
private function onTimer(e:TimerEvent):void {
ApplicationFacade.getInstance().sendNotification(Constants.REPTITIVE_ACTION_NOTIFICATION));
}
}
}
This code assumes that you have your Concrete facade named ApplicationFacade, and have registered a notification using a String constant that is referenced from a class called constants.
Then in an appropriate place (maybe in your startup command) you can add:
RepetitiveSingleton.getInstance().start();
Hope this helps you.
IMO, the timer belongs in a mediator. Let it- well, mediate the asynch process messaging. It will be a little state machine to make sure everything is running smoothly. Commands still do the heavy lifting, it just sits around like a 911 operator.