Java run code on exit

How to Exit JFrame on Close in Java Swing

In this tutorial, we will focus on learning how to exit JFrame on close in Java Swing. I will be discussing various methods in this tutorial in detail.

Exit JFrame on Close in Java Swing

We need to use the Java Swing library to create a JFrame, thus we must first import the library into our code. The Java Swing Library is used to create window-based applications with various powerful components such as JFrame which we will be using to create a frame.

Do read this article, which clearly explains the Java Swing Library, its components such as JLabel, the creation of a JFrame, inbuilt- methods, its parameters, etc.

Creating a Java JFrame

JFrame is a class of the javax.swing package which is a container that provides a window on the screen. We create a JFrame with the title “Exit on Close Example” and use the setVisible(true) function to display the frame. We specify the location of the frame using the setBounds() function.

Читайте также:  Javascript array в строку

Let’s see the code:

JFrame frame = new JFrame("Exit on Close Example"); // Creation of a new JFrame with the title frame.setVisible(true); // To display the frame frame.setBounds(100, 200, 350, 200); // To set the bounds of the frame.

How to Exit JFrame on Close in Java Swing

We have created a plain empty JFrame with our title successfully. Now, we have to exit JFrame on close. One simple way of doing this is clicking the cross button on the top right corner of the frame which closes the frame but the application or code will still be running in the background.

The efficient way of closing the JFrame is that we use the inbuilt method provided by the JFrame class i.e., using the JFrame.setDefaultCloseOperation(int) method. We use this method to change the behavior of the default JFrame which hides it instead of disposing of it when the user closes the window.

Two Approaches on Closing JFrame

Method 1: Using the WindowConstants

The simplest and most used technique is to use WindowConstants.EXIT_ON_CLOSE as a parameter. We must extend the JFrame class to our main class to use this. By using this, it closes the JFrame window completely and also frees the memory.

Method 2: Using the JFrame Constants

We have various constants defined by javax.swing.JFrame to close the JFrame as per our requirements. They are :

  • JFrame.EXIT_ON_CLOSE — A System.exit(0) will be executed which will exit the entire code and the frame.
  • JFrame.DISPOSE_ON_CLOSE — It will dispose of the frame but keep the code running.
  • JFrame.DO_NOTHING_ON_CLOSE — The frame will not be closed. It basically does nothing.
  • JFrame.HIDE_ON_CLOSE — This is the default one. It will hide the frame but keep the code running.

I have implemented both methods in the code for greater understanding.

Let’s see the code:

import javax.swing.*; public class ExitOnClose extends JFrame < public static void main(String[] args) < JFrame frame = new JFrame("Exit on Close Example"); // Creation of a new JFrame with the title frame.setLayout(null); // To position our components frame.setVisible(true); // To display the frame frame.setBounds(100, 200, 350, 200); // To set the locations of the frame. //------------------------------------------------ //To Terminate the JFrame and the code on close //------------------------------------------------ //METHOD-1 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //METHOD-2 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); >>

Thanks for reading! I hope you found this post useful!

Источник

Perform an action when exiting a Java-based Android application

To resolve the issue, you can utilize the amazing realm of asynchronous events. For instance, assuming your Text to Speech object is available, you can subscribe to an event. This approach is asynchronous because your program can perform other tasks while you wait for the notification of the subscribed event occurrence.

Android waiting on something

I am trying to figure out how to make a program pause until an event is completed before triggering another event. For instance, I have a text-to-speech function that needs to finish speaking before the Google voice recognizer is activated. Currently, both events occur simultaneously, causing the recognizer to pick up the speech. I have researched solutions on this platform, but the explanations were not straightforward. Can someone assist me with this issue?

Here’s a code snippet that I experimented with.

protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() < @SuppressWarnings("deprecation") @Override public void onInit(int status) < if(status != TextToSpeech.ERROR)< tts.setLanguage(Locale.UK); tts.speak("Welcome", TextToSpeech.QUEUE_FLUSH, null); >> >); if(!(tts.isSpeaking())) < startVoiceRecognitionActivity(); >> private void startVoiceRecognitionActivity() < Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Up"); startActivityForResult(intent, REQUEST_CODE); >@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) < matches = data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); if (matches.contains("list"))< Intent gotoList = new Intent(MenuActivity.this, ListActivity.class ); startActivity(gotoList); >> super.onActivityResult(requestCode, resultCode, data); > 

Enter the fascinating realm of events that occur without synchronicity.

To achieve your desired outcome, it is not advisable to adopt a «wait and see» approach as it can lead to stagnation. Instead, the key is to adopt an active «listening» approach.

In Android, if a process like Text To Speech takes a while, you need to keep an ear out for an event.

Upon examining the documentation for the Text To Speech object, it is evident that it allows for the utilization of a listener for various purposes. This can be observed through the following links: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html#setOnUtteranceProgressListener(android.speech.tts.UtteranceProgressListener) and http://developer.android.com/reference/android/speech/tts/UtteranceProgressListener.html.

Assuming your Text to Speech object is identified as tts , you would perform the following action.

tts.setOnUtteranceProgressListener(new UtteranceProgressListener() < public void onDone(String utteranceId) < // The text has been read, do your next action >public void onError(String utteranceId, int errorCode) < // Error reading the text with code errorCode, can mean a lot of things >public void onStart(String utteranceId) < // Reading of a sentence has just started. You could for example print it on the screen >>); 

The process of subscribing to an event is asynchronous as it allows your program to perform other tasks while waiting for a notification about the subscribed event. The notification is triggered by the occurrence of the event that has been subscribed to.

Then for example when you do

Upon completion, the onDone method will trigger the listener and initiate the voice recognizer.

Источник

Example of Java Code Demonstrating the Usage of ‘void’ on Program Exit

If, for some reason, the shutdown hook internally invokes exit() again (such as in the case of an exception that necessitates program termination), you would also invoke it there. Of course, before exiting, you could always flush and redirect back to stdout and stderr.

JNA Error at Program Exit

 char **p = (char**)malloc( r.size() * sizeof(char *) ); 

This showcases the frequency of my current usage of malloc!

Java — Should I call Process.destroy() if the process ends, You wouldn’t think it should be necessary. You would think if the process has returned an exit code it has called exit () or returned out of main, so …

What can cause Java to keep running after System.exit()?

This scenario can occur when your code (or a library you utilize) contains a shutdown hook or a finalizer that fails to complete properly. «»».

A more forceful method to initiate a shutdown is by executing the following command, but it should be reserved for exceptional circumstances.

The parent process assigns a separate thread to handle each of the child’s STDOUT and STDERR, forwarding the output to a log file. As far as I can tell, these threads are functioning correctly as we are observing the expected output in the log.

I encountered a similar issue with my program not disappearing from task manager when I was consuming the stdout/stderr. In my scenario, the javaw.exe process would remain even if I closed the stream that was listening before calling system.exit(). It was odd because the program was not writing anything to the stream.

The approach I took was to flush the stream instead of closing it before exiting. Alternatively, you can flush the stream, redirect it back to stdout and stderr, and then exit.

Verify the existence of a deadlock.

Runtime.getRuntime().addShutdownHook(new Thread(this::close)); System.exit(1); 

The System.exit() function invokes both the shutdown hook and finalizers. Therefore, if your shutdown hook internally calls the exit() function again, such as in the case where close() throws an exception and you want to terminate the program, the exit() function will also be invoked.

public void close() < try < // some code that raises exception which requires to exit the program >catch(Exception exceptionWhichWhenOccurredShouldExitProgram) < log.error(exceptionWhichWhenOccurredShouldExitProgram); System.exit(1); >> 

While it is considered beneficial to throw the exception, certain individuals may opt to log the error and terminate the program.

It is important to note that Ctrl+C will not be effective in the presence of a deadlock, as it also invokes the shutdown hook.

In any case, if it is true, this issue can be resolved using this alternative solution.

private static AtomicBoolean exitCalled=new AtomicBoolean(); private static void exit(int status) < if(!exitCalled.get()) < exitCalled.set(true); System.exit(status); >> Runtime.getRuntime().addShutdownHook(new Thread(MyClass::close)); exit(1); > private static void close()

I believe that the aforementioned exit() version should be exclusively written using the System.exit() approach (possibly as a JDK PR). This is because, in my observation, there is no practical reason to entertain a deadlock in System.exit() .

Java Exit on Windows Shutdown, The happens either when your program terminates or because of a system-wide event, such as a user log-off or a shut-down. All you need to do is …

Should I call Process.destroy() if the process ends with exit code 0?

It seems that your program is generating a significant output. When you execute a program in the background, it will write to the buffer, which may have a small size of just a few KB. Once the buffer reaches its limit, it will pause and wait for the consumer, in this case, your program, to read the output. This is applicable to both standard out and error.

If you fail to consume the output and error of your spawned program, it can result in an endless wait. Since you are waiting for the exit code, which will not occur, a deadlock is encountered.

My recommendation is to utilize ProcessBuilder, which allows you to redirect the error to the output. It is advisable to read both the error and output until the end before waiting for the exit code.

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2"); pb.redirectErrorStream(true); File log = new File("log"); pb.redirectOutput(Redirect.appendTo(log)); Process p = pb.start(); // no need to copy the output int exit = p.waitFor(); 

Источник

System.exit() в Java – что это?

Java – язык программирования, имеющий множество приложений. При программировании для одного из этих приложений вы можете застрять на каком-то этапе этой программы. Что делать в этой ситуации? Есть ли способ выйти в этой самой точке? Если эти вопросы вас беспокоят, вы попали в нужное место.

Что вы можете сделать, это просто использовать метод System.exit(), который завершает текущую виртуальную машину Java, работающую в системе.

Как вы выходите из функции в Java?

Вы можете выйти из функции, используя метод java.lang.System.exit(). Этот метод завершает текущую запущенную виртуальную машину Java (JVM). Он принимает аргумент «код состояния», где ненулевой код состояния указывает на ненормальное завершение.

Если вы работаете с циклами Java или операторами switch, вы можете использовать операторы break, которые используются для прерывания / выхода только из цикла, а не всей программы.

Что такое метод System.exit()?

Метод System.exit() вызывает метод exit в классе Runtime. Это выходит из текущей программы, завершая виртуальную машину Java. Как определяет имя метода, метод exit() никогда ничего не возвращает.

Вызов System.exit (n) фактически эквивалентен вызову:

Функция System.exit имеет код состояния, который сообщает о завершении, например:

  • выход (0): указывает на успешное завершение.
  • выход (1) или выход (-1) или любое ненулевое значение – указывает на неудачное завершение.

Исключение: выдает исключение SecurityException.

Примеры

package Edureka; import java.io.*; import java.util.*; public class ExampleProgram< public static void main(String[] args) < int arr[] = ; for (int i = 0; i < arr.length; i++) < if (arr[i] >= 4) < System.out.println("Exit from the loop"); System.exit(0); // Terminates JVM >else System.out.println("arr["+i+"] = " + arr[i]); > System.out.println("End of the Program"); > >

Выход: arr [0] = 1 arr [1] = 2 arr [2] = 3 Выход из цикла

Объяснение: В приведенной выше программе выполнение останавливается или выходит из цикла, как только он сталкивается с методом System.exit(). Он даже не печатает второй оператор печати, который говорит «Конец программы». Он просто завершает программу сам.

package Edureka; import java.io.*; import java.util.*; public class ExampleProgram< public static void main(String[] args) < int a[]= ; for(int i=0;i > > >

Вывод: array [0] = 1 array [1] = 2 array [2] = 3 array [3] = 4 Выход из цикла

Объяснение: В приведенной выше программе она печатает элементы до тех пор, пока условие не станет истинным. Как только условие становится ложным, оно печатает оператор и программа завершается.

Источник

Оцените статью