I have a SWING form and when I close the application I want to save data to a text file.
This is the code generated by Swing which I cannot modify:
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosed(java.awt.event.WindowEvent evt)
{
formWindowClosed(evt);
}
});
Here is my custom implementation of formWindowClosed. The problem is that the app closes without executing formWindowClosed.
Isn't formWindowClosed the method where I want to put the code that gets executed before the app closes ?
formWindoClosed implementation:
private void formWindowClosed(java.awt.event.WindowEvent evt)
{
System.out.println("Message");
brain.getBirou().getProbaRepo().WriteParticipantToTXT();
}
If you want to execute code before the process exits, you have to set the default close operation to WindowConstants.DISPOSE_ON_CLOSE then in the listener method save your file and then call System.exit(0); when you're done.
Also "Swing" doesn't generate code by itself. Maybe you should write your GUI code for your self, by hand. Then of course you can modify anything.
You have to have the possibility to change exit behavior of your window, so setting it to dispose on close should help. Maybe you should look up where you can change it in your IDE. (Or just open it with a text editor...)
you can use formWindowClosing instead.
To do this through the Netbeans IDE GUI Builder:
Go to Design view and right-click the [JFrame] inside the Navigator window. Go to events and select the event you want to add.
Remember to mark the frame as DO_NOTHING_ON_CLOSE in the defaultCloseOperation property.
Related
I am trying to set the default close operation in NetBeans 8.0.2 (in Ubuntu 14.04 on an older Asus gaming laptop.) My program is very large but uses no JFrame or java.swing components.
I merely need to save some values when the "x" in the lower right corner is clicked (this is one usual way to stop execution of a java program in NetBeans.)
I found suggestions that involved swing & JFrame, but it wasn't clear just where to insert the code:
DefaultApplicationView view = new DefaultApplicationView(this);
javax.swing.JFrame frame = view.getFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent e){
System.out.println("CLOSING");
}
}
show(view);
I also found a set of instructions that I think I would prefer to use, but the post is old enough that my NetBeans doesn't have the tabs/menu-items referred to:
Set Window to Design Mode by clicking the 'Design' Tab
In the Navigator: Right click the 'JFrame' -> 'Properties'
In the Properties Tab: Set 'defaultCloseOperation' (top of the list) to 'DO_NOTHING'
Select 'Events' Tab
Scroll down to 'windowClosing'
Click on the "..." button on the right of the event to bring up the custom editor
Click 'Add...' and name the handler (i.e. custom function that you want to have execute on click of the 'X', or window close event).
Click 'Ok'
Netbeans now automatically creates the function and takes to you the function body in the source view
Now simply add what you want to do here: eg. dispose(), or system.exit or pintln(), or whatever your heart desires, as long as its JAVA and makes sense to the app.
Then there are a few other possibly relevant posts, but they all explicitly involve JFrame and/or swing. (Am I ignorant of some fact such as "All NetBeans java applications use JFrame", or some such?)
A pared down example of code for what I'm trying to do would be:
public class MyApp{
public static void main(String[] args){
loadMyVariables();
// do some work that changes variables' values
// during this work user clicks the 'x' box to halt execution
// I need then automatically to save the variables' new values
}
// needs to be called by the OS or GUI when execution is halted by user
public static void saveMyVariables{
// here the usual printStream stuff saves some values to a file
System.exit(0);
}
public static void loadMyVariables{
// here the usual Scanner stuff reads some values from a file
}
}
(I need help setting the tags for this, so I'm doing as instructed and asking the community.)
THANKS
I am making a library where an application can use it to capture a selection of a screen and convert it to an image, like Gyazo.
This library is not the application itself, but only the tool that returns the File or BufferedImage object to the application.
I want the application to be simple as this:
Bootstrap b = new Boostrap(new GifCapturer());
b.beginCapture(); // user selects an area
File file = b.getFile();
But how can I make the application wait till the library returns the object? as you see the beginCapture method should activate the JFrame where the user will select an area to capture.
Do I need to sleep the thread? or use listeners design?
The beginCapture method starts a jframe window, where the user is able to select an area of the screen. Once selected, the library will convert the selected area to an object and set it as a local variable. So when you will use getFile it ill return the captured image. But the thing is, i need to make sure that the image was selected before getFile call gets executed, and wait instead but im not sure how.
Sorry if the question is not detailed, im on phone.
Please let me know if you need more information.
Implement a listener, that is invoked as soon the selection is ready. Put your File file = b.getFile(); code into the listener.
The code of your JFrame would be necessary to give a more detailed answer.
I have decided to use a Listener with a own built listener class, and interface.
Create an interface which you will use to get the data, or that will get know when the listener gets called, like this in my case:
public static void main(String[] args) throws AWTException {
Bootstrap b = new Bootstrap(new GifCapturer());
b.beginCapture(new ScreenCaptureCallback() {
#Override
public void captureEnded(File file) {
System.out.println("done!");
}
});
}
I'm working on a Java7 Swing "wizard" type of project that needs to validate a web address before continuing on to the next step of the wizard. The validation requires accessing a URL over the internet to verify that expected resources are available. In some cases, this can take a few seconds which can be long enough to confuse a user.
As a quick solution to this, I would like to disable the "next" button and change the display text while the validation is running so the user knows that the wizard is working and not hung up on anything. The problem is that when I add the code to modify the JButton, none of the changes happen until after the validation has completed. This is the case even if I change the button and call revalidate() before I execute the validation methods.
Here is an excerpt of what I've tried:
// create next button
next = new JButton("Next", new ImageIcon(getClass().getResource("/navigate_right.png")));
next.setActionCommand("MYACTION");
next.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Is this the event dispatch thread? "
+ javax.swing.SwingUtilities.isEventDispatchThread());
System.out.println("Changing button");
next.setEnabled(false);
next.setText("Testing Connection");
next.getRootPane().revalidate();
System.out.println("Validating Service");
boolean isValidLocation = ServiceValidator.serviceExists(locationField.getText());
// ...etc...
When I run this code, the lines "Changing button" and "Validating Service" both get printed before the actual button changes in the display. How can I get the JButton to change before System.out.println("Validating Service"); is printed?
The problem is that when I add the code to modify the JButton, none of the changes happen until after the validation has completed.
Your code is executing on the EDT, so you long running code prevents the GUI from repainting itself until the task is finished executing. You need to use a separate Thread for the long running task, maybe a SwingWorker. Read the section from the Swing tutorial on Concurrency for more information.
I'm trying to get and action event to fire on my HelloWorld. im using the GUI and when it auto creates the:
protected void onMain_Button1Action(Component c, ActionEvent event) {
// If the resource file changes the names of components this call will break notifying you that you should fix the code
super.onMain_Button1Action(c,event);
}
I know its not going to work because there is no void of the same type in the superclass.
protected void onMain_Button1Action(Component c, ActionEvent event) {
// If the resource file changes the names of components this call will break notifying you that you should fix the code
Dialog.show("Test", "it works", "OK",null);
}
And I'm still getting nothing. I've looked for other tutorials on how to use codenames as one but i cant find any. And I dont get the one made by the author. if any one can toss me a line i would be most appreciative.
You need to save the resource file in the designer and NOT delete the call to super. If you are using Eclipse you should refresh the project after saving in the designer using F5.
So I made a standard swing application in Netbeans 6.8 but I can't find where the resource file that defines the localized string for the Exit menu item under File.
It doesn't seem to be defined among the resource files in <project>/resources. Is this a standard string somewhere or am I missing something?
The "Exit" string doesn't get defined as a localized string like the File menu item -- it gets generated into code through the Netbeans GUI builder. That is why you don't see it in the properties file.
If you open the file {ProjectName}View.java you can see that it gets defined through the netbeans GUI builder. Click on the file menu and then the exit menu item in the GUI builder and you can look at the properties of the swing item. One of the properties is the text of the JMenuItem.
Then these properties get generated into code.
Are you just trying to shut down your application in such a way that you are able to do clean-up tasks before the system shuts down? If so then on the Java Sun site they say that you need to override the shutdown method; specifically :
#Override
protected void shutdown() {
// The default shutdown saves session window state.
super.shutdown();
// Now perform any other shutdown tasks you need.
}
This is located at this location