Skip to content
Advertisement

How to display the color of a button last clicked in java?

It is necessary that when the application is restarted, the last color that was displayed is displayed.

JavaScript

Now you need to display the color that was before closing when you restart the window. That is, if the color of the button was red to display red. If the color of the button is normal, the normal color is displayed.

Advertisement

Answer

First the code, then the explanations.

JavaScript
  • In method main I explicitly launch the Event Dispatch Thread (EDT). The parameter to method invokeLater is an instance of a class that implements interface java.lang.Runnable (which class The does). Hence method invokeLater will call method run in class The.
  • Method run (in class The) calls method createAndDisplayGui. In this method I build the GUI.
  • Method createAndDisplayGui calls method init. Method init tries to read the file that stores the last background color of st1 (i.e. the JButton). Notice that the code uses try-with-resources and multi-catch. Also note that the first time you run the app, the file may not exist. Hence I ignore FileNotFoundException.
  • You only really want to save the background color of st1 when you exit the app. Hence I added a WindowListener. Method windowClosing is called just before the JFrame is closed.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement