Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Incoherence
May 22, 2004

POYO AND TEAR

Phillyt posted:

How would you distinguish between the three words at the top to make it the name? I am probably going to just write the program assuming /t as the token and just get partial credit. Seems a lot easier.
Already covered to some extent, but what I was trying to get you to say is the following:
1. None of the fields except for the name can have spaces in them.
2. Fields are separated by something, just not necessarily a tab (it could very well be a space), and that "something" obviously doesn't belong to any of the other fields. Ideally, fields are separated by some sort of white space.

Given that, if there are N words in the line, the Nth word is the email address, the N-1th is the login ID, the N-2nd is the student ID, and the first N-3 words are the name.

Another acceptable answer would be that the student ID is in a specified format (which you could look for, and everything before it is obviously the name), and the email address is in a specified format which you could pull out.

Incoherence fucked around with this message at 09:07 on May 23, 2008

Adbot
ADBOT LOVES YOU

shodanjr_gr
Nov 20, 2007
Yet another SWING question (i managed to hack around and get my previous one fixed :P).

Is it possible to somehow add the SAME component (meaning, the same instance of a component) to two separate containers?

code:
JLabel my_label = new JLabel("Foo");
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
panel_1.add(my_label);
panel_2.add(my_label);
The above results in the label (or whatever component) being added only to panel_2...


edit: Second question, why the heck does the JVM get "clogged up" (for lack of a better term), when it captures mouse events on a container?

I move my mouse, over my container, and some times fail to get an update on it's position. Then i wiggle it around a bit, and get about 10-15 updates together...This really kills my GUI (im changing stuff inside my container, depending on the mouse's position).

shodanjr_gr fucked around with this message at 15:49 on May 23, 2008

such a nice boy
Mar 22, 2002

shodanjr_gr posted:

Yet another SWING question (i managed to hack around and get my previous one fixed :P).

Is it possible to somehow add the SAME component (meaning, the same instance of a component) to two separate containers?
No.

shodanjr_gr posted:

edit: Second question, why the heck does the JVM get "clogged up" (for lack of a better term), when it captures mouse events on a container?

I move my mouse, over my container, and some times fail to get an update on it's position. Then i wiggle it around a bit, and get about 10-15 updates together...This really kills my GUI (im changing stuff inside my container, depending on the mouse's position).
Threading stuff. It's complicated. Read this:
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

shodanjr_gr
Nov 20, 2007
Thanks for the replies. I figures it was something related to the dispatcher thread. Ill look into it more later.

I got another one (which probably isnt exclusively Java related, but what the heck).

Ive got a library that allows for the execution of Win32 Native Call via Java. However, i cant for the love of my life find a LIST of all the possible API calls. What i want to do, is open a file, or open the directory a file is in. (mind you that as far as native WINDOWS program goes, ive done very very little, so i dont know my way around it).

csammis
Aug 26, 2003

Mental Institution

shodanjr_gr posted:

Ive got a library that allows for the execution of Win32 Native Call via Java. However, i cant for the love of my life find a LIST of all the possible API calls. What i want to do, is open a file, or open the directory a file is in. (mind you that as far as native WINDOWS program goes, ive done very very little, so i dont know my way around it).

You're batshit insane if you want to do filesystem stuff via the Win32 API rather than Java (which, on Windows, just wraps the Win32 calls), but MSDN is your friend.

shodanjr_gr
Nov 20, 2007

csammis posted:

You're batshit insane if you want to do filesystem stuff via the Win32 API rather than Java (which, on Windows, just wraps the Win32 calls), but MSDN is your friend.

I dont wanna do file system operations (copying/deleting etc). What i want to do is run/open files (get a PDF to open in word, get an mp3 to open in winamp etc) and to open Explorer windows for specific directories.

As far as i am aware, the Java API doesnt have provisions for the above.

Also, cheers for the link, ill look into it right away :)

csammis
Aug 26, 2003

Mental Institution
Opening files in programs and opening Explorer to certain directories has absolutely nothing to do with the Win32 API. It's all about command line arguments to those particular programs. There's no comprehensive list, just google for the programs you want and how to open files with them via command line.

shodanjr_gr
Nov 20, 2007

csammis posted:

Opening files in programs and opening Explorer to certain directories has absolutely nothing to do with the Win32 API. It's all about command line arguments to those particular programs. There's no comprehensive list, just google for the programs you want and how to open files with them via command line.

If i go to the command prompt and do a "foo.jpg", the image will open in the default program that ive selected to handle that kind of file. I dont have to use the filename as an argument while running the program...(which seems pretty reasonable, since it would make any sort of search application impossible to develop - which is what i am making).

That's what i want to accomplish. But in java.

csammis
Aug 26, 2003

Mental Institution

shodanjr_gr posted:

If i go to the command prompt and do a "foo.jpg", the image will open in the default program that ive selected to handle that kind of file. I dont have to use the filename as an argument while running the program...(which seems pretty reasonable, since it would make any sort of search application impossible to develop - which is what i am making).

That's what i want to accomplish. But in java.

That only works because Windows Explorer has a file extension association to open things that end with .jpg by running "mspaint %filename%" :eng101:

Also, what the hell do you mean it would make a search application "impossible to develop" - how would you not have the filename as a search result? Maybe you need to be very clear about what you're doing.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

csammis posted:

That only works because Windows Explorer has a file extension association to open things that end with .jpg by running "mspaint %filename%" :eng101:

Maybe there's a Java library to interface with the Windows registry? :v:

shodanjr_gr
Nov 20, 2007

csammis posted:

That only works because Windows Explorer has a file extension association to open things that end with .jpg by running "mspaint %filename%" :eng101:

Also, what the hell do you mean it would make a search application "impossible to develop" - how would you not have the filename as a search result? Maybe you need to be very clear about what you're doing.

I am writting a small desktop search app. Im getting my results fine and dandy, and what i am trying to do, is launch my results, through my GUI. So if i get a .doc as a result, i wanna be able to launch whatever app my user has associated with .doc files (be it openoffice, ms word or wordpad). I also want to be able to do an "open containing folder" operation for each of my results.



quote:

Also, what the hell do you mean it would make a search application "impossible to develop" - how would you not have the filename as a search result? Maybe you need to be very clear about what you're doing.

The way you worded your previous reply, i got the impression that you have to know beforehand what programs are used for each filetype, and then issue a command-line call for those programs (passing the file to be opened as a parameter), which would make an application impossible to develop, considering the limitless combinations of file types and applications.



edit:

Found what i needed

code:
Runtime run = Runtime.getRuntime();
Process p = run.exec("cmd.exe /C "+this.my_file.getCanonicalPath());
This does what i want exactly wanted (with a drawback of the spawned application instances being child instances to the original java app...so the app doesnt completely shutdown until the children are closed...any way to get around that?).

shodanjr_gr fucked around with this message at 18:14 on May 24, 2008

1337JiveTurkey
Feb 17, 2005

Avenging Dentist posted:

Maybe there's a Java library to interface with the Windows registry? :v:

I haven't messed around with it personally, but you want java.util.preferences for that. True to Java form, it's designed to be cross-platform and scalable so it also supports LDAP and XML config files.

epswing
Nov 4, 2003

Soiled Meat

shodanjr_gr posted:

Found what i needed

code:
Runtime run = Runtime.getRuntime();
Process p = run.exec("cmd.exe /C "+this.my_file.getCanonicalPath());

You'll probably want to use ProcessBuilder.

Fehler
Dec 14, 2004

.
Speaking of executing commands, is there any way to do something like "mailto:foo@bar.com?subject=1" in Java?

When I do Runtime.getRuntime().exec('mailto:foo@bar.com?subject=1'); I get this exception: "java.io.IOException: Cannot run program "mailto:foo@bar.com?subject=1": CreateProcess error=2"

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

Fehler posted:

Speaking of executing commands, is there any way to do something like "mailto:foo@bar.com?subject=1" in Java?

When I do Runtime.getRuntime().exec('mailto:foo@bar.com?subject=1'); I get this exception: "java.io.IOException: Cannot run program "mailto:foo@bar.com?subject=1": CreateProcess error=2"

If you're trying to send emails, you can use the java mail API which provided you have all the correct SMTP settings can send email.

shodanjr_gr
Nov 20, 2007

shodanjr_gr posted:

I move my mouse, over my container, and some times fail to get an update on it's position. Then i wiggle it around a bit, and get about 10-15 updates together...This really kills my GUI (im changing stuff inside my container, depending on the mouse's position).

Im coming back to this. I read the link on Sun's dev pages about SWING and threads.

So i decide to spin my MouseInputListener into a separate thread. This gives me a notable improvement in fluidity, but still, it's not as good as i want to be...i still find that my mouse goes over my component and events dont register, or are late to register, etc.

Ive tried increasing the priority of the thread, but it doesnt seem to help.

Is there a way i can make this better?

edit:

Another issue i seem to have is that the MouseInputListener seems to ignore MouseClicked and MousePressed/Released events that happen inside the JScrollPane...They dont get handled at all...Any ideas?

shodanjr_gr fucked around with this message at 20:16 on May 25, 2008

mister_gosh
May 24, 2002

I inherited some code that uses reflection (which I've never used before; I guess part of my excuse is that I don't code in Java that much). Anyways, this code uses it and I'm not sure why. What is its purpose? The only time it uses it it is to use the invoke method (set it to null). I read up on reflection but I think I'm not getting it because I'm trying to equate its use to this example. Can anyone lend me a mental hand?

code:
public static void doSomething(Foo foo, String name, java.lang.reflect.Method methodStatic) {
  try {
    methodStatic.invoke(null,null);
  } catch (Exception e) {
    // do something and return
  }
    
  try {
    // do some stuff, like get the name variable value, etc
    doSomething(foo, name, methodStatic);
  } catch (Exception e) {
  } finally {
  }
}     

poopiehead
Oct 6, 2004

It looks like it will call the method repeatedly until it throws an exception, which is kind of weird. The point of reflection here might just be to act as a function pointer which is kind of awkward to do in Java. This method can work with any static void method with no arguments..... but I don't think there's really enough information there to actually know what's going on. It might be clearer with the full code of the method and where it's being called.

poopiehead fucked around with this message at 02:14 on May 27, 2008

1337JiveTurkey
Feb 17, 2005

What that's doing is getting a static or class method and then calling it without any arguments. Since a static method has no underlying object to invoke it upon, the argument may be null. Since the static method also has no parameters, that's why you're seeing methodStatic.invoke(null, null). The reason for this is most likely because the person writing the code wanted to be able to call the same method from a class specified and loaded at runtime. That code would work, but it's not the standard idiom, where you'd define an interface and then instantiate the interface with a zero-argument constructor.
code:
MyInterface myInstance = null;
try {
	// JAR files are accessed through a URL object
	ClassLoader cl = new URLClassLoader(myURLs);
	Class<MyInterface> myClass = cl.loadClass(myClassName);
	// Reflective equivalent of zero-arg constructor
	myInstance = myClass.newInstance();
// This keeps the containing class from needing to declare these exceptions
} catch (SecurityException e) {
	throw new RuntimeException("Insufficient permissions.", e);
} catch (ClassNotFoundException e) {
	throw new RuntimeException("Class doesn't exist.", e);
} catch (InstantiationException e) {
	throw new RuntimeException("Class has no zero-arg constructor.", e);
} catch (IllegalAccessException e) {
	throw new RuntimeException("Cannot access constructor.", e);
}
// At this point you've got a regular object ready for use
myInstance.myMethod();
This does seem a bit more elaborate, but the advantage is that at the bottom you don't need to worry about myInstance.myMethod() ever failing for any reason related to reflection. At that point it's virtually indistinguishable from any normal class except for the issue of their having differing ClassLoaders (This should never be an issue in any remotely sane program). The performance is also substantially better if you're calling that method very often since only instantiation is dealt with through reflection.

Led
Jan 30, 2004
Sjoebiedoewap
I don't know if this is the right thread, but does anyone want to test my Java applet for me ?
I heard some people had problems with it, especially on other operating systems.
(I've only tested it locally on windows)

it's at http://www.supercheckmate.com (but it has nothing to do with chess :))

Cubiks
Aug 31, 2005
I wish I had something witty to put here...

shodanjr_gr posted:

Im coming back to this. I read the link on Sun's dev pages about SWING and threads.

So i decide to spin my MouseInputListener into a separate thread. This gives me a notable improvement in fluidity, but still, it's not as good as i want to be...i still find that my mouse goes over my component and events dont register, or are late to register, etc.

Ive tried increasing the priority of the thread, but it doesnt seem to help.

Is there a way i can make this better?

edit:

Another issue i seem to have is that the MouseInputListener seems to ignore MouseClicked and MousePressed/Released events that happen inside the JScrollPane...They dont get handled at all...Any ideas?

I don't understand what you mean by "spin my MouseInputListener into a separate thread". Listeners of all sorts run pretty much exclusively on the EDT, are you doing some trickery to then do the actual work in a separate thread or something?

When you attach a MouseListener or other listener to a java swing component, all the work done by that listener is called from the EDT, no matter what thread the listener was created on, attached on, whatever. The only way I can think of to spin the work onto a separate thread would be to use some type of inter-thread communication when your listener registers an event, which would be kinda awkward, but feasible.

Without seeing any of your code, I can't tell if that is what you are doing or not. If not, then you may still be running the listener events on the EDT. If you are doing a lot of painting as well, that could clog the EDT so that mouse events bunch up. I've run into this problem a few times, doing custom painting but refreshing it too quickly.

I guess the take-away message is that all GUI work occurs on the EDT, so if you're experiencing slowdown then some part of your GUI displaying/updating is taking too long, or being called too often. I'm sorry I can't really give you more direction than that, I hope it's helpful.

shodanjr_gr
Nov 20, 2007
I have profiled my code and fixed some painting issues that were holding up my GUI, but still the issue remains.



There is a LARGE irregularity in recieving MouseMoved Events, especially if move the mouse fast around my component. Some times MouseEvents are missed, other times i get 20 events "jammed" together...

I deduced from a reply above, that creating a separate thread for the mouseListener would maybe make things faster (since i am doing some math when i handle the MouseMoved events to determine what's under the mouse), but it didnt help that much...

Also i want to note that this happens ONLY with MouseMoved events, everything else works fine and dandy. Repainting is instantaneous, handling of keyboard events and updating of the GUI as well.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Led posted:

I don't know if this is the right thread, but does anyone want to test my Java applet for me ?
I heard some people had problems with it, especially on other operating systems.
(I've only tested it locally on windows)

it's at http://www.supercheckmate.com (but it has nothing to do with chess :))

Well it loads and works on my Kubuntu 8.0.4 x64 machine. Also it said that a picture of a flower was indecent. :confused:

edit: I forgot to mention I'm running Sun's Java 6 and Firefox 2 on this computer.

Janitor Prime fucked around with this message at 20:52 on May 28, 2008

1337JiveTurkey
Feb 17, 2005

Led posted:

I don't know if this is the right thread, but does anyone want to test my Java applet for me ?
I heard some people had problems with it, especially on other operating systems.
(I've only tested it locally on windows)

it's at http://www.supercheckmate.com (but it has nothing to do with chess :))

OSX 10.5 on a G5 iMac failed to initialize the applet and provided no error console message. I'm running Java 5 and have enough porn lying around to cripple some filesystems.

Phillyt
Dec 2, 2006

by Tiny Fistpump
I have a question that I haven't been able to figure out. I have a Java windows application with Swing and all that. I have a check box on my window. When I click that check box, how do I make an event that makes more check boxes? The typical example is I have a menu, I click Hamburger, and then more check boxes come with things like lettuce, tomatoes, etc. Thanks.

shodanjr_gr
Nov 20, 2007

Phillyt posted:

I have a question that I haven't been able to figure out. I have a Java windows application with Swing and all that. I have a check box on my window. When I click that check box, how do I make an event that makes more check boxes? The typical example is I have a menu, I click Hamburger, and then more check boxes come with things like lettuce, tomatoes, etc. Thanks.
Have a JPanel somewhere inside your frame, since this will make it easier to add-remove stuff.
code:
JPanel my_optionpanel = new JPanel();
this.getContentPane().add(my_optionpanel);
Inside the Combobox handler you can do something like:

code:
my_optionpanel.removeAll();//clear what was previously in the panel
JComboBox lettuce_comboBox = new JComboBox("Lettuce");
JComboBox tomato_comboBox = new JComboBox("Tomatos");
//add handlers for the combo boxes here
my_optionpanel.add(lettuce_comboBox);
my_optionpanel.add(tomato_comboBox);

mister_gosh
May 24, 2002

I'm unclear on the concept here. I want to put stuff into a HashMap and at a later time, retrieve the objects from the map by iterating through it and processing every object. I want it to be in the order that I originally put them in.

I realized when I did this that a HashMap is unordered, so I read up on the Collections and decided to try the TreeMap. Doing so put it in a different, but still not correct, order.

Is there another Collection I can use that allows me to store key->object pairs but maintain them during an iteration process (index(0) through index(x))?

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

mister_gosh posted:

I'm unclear on the concept here. I want to put stuff into a HashMap and at a later time, retrieve the objects from the map by iterating through it and processing every object. I want it to be in the order that I originally put them in.

I realized when I did this that a HashMap is unordered, so I read up on the Collections and decided to try the TreeMap. Doing so put it in a different, but still not correct, order.

Is there another Collection I can use that allows me to store key->object pairs but maintain them during an iteration process (index(0) through index(x))?

java.util.LinkedHashMap seems to be what you want:

API Docs posted:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

poopiehead
Oct 6, 2004

LinkedHashMap

mister_gosh
May 24, 2002

Thanks!

ynef
Jun 12, 2002

shodanjr_gr posted:

If i go to the command prompt and do a "foo.jpg", the image will open in the default program that ive selected to handle that kind of file. I dont have to use the filename as an argument while running the program...(which seems pretty reasonable, since it would make any sort of search application impossible to develop - which is what i am making).

That's what i want to accomplish. But in java.

At least in previous versions of Windows, you had the "start" command. I don't run Windows, so I wouldn't be able to check if this is still the case. "start filename.something" would be equivalent to double clicking the file in Explorer. This works (worked?) for folders also. So, all you'd have to do is find out the file name and send that as the argument to "start", and you're done. My guess would be that "filename.something" is simply interpreted as "start filename.something" by the cmd shell.

Why is something this Windows-centric developed in Java, though? :)

ssergE
Sep 10, 2001

No longer a stupid baby. Now a stupid teenager.
Hello All,

I am just about to start on some Java projects again, and was wondering what a good book would be for somebody with strong programming knowledge. I am after something akin to the classic K&R C book, but for Java. It should cover Java 1.6.

I own the 6th (I think - they are in storage ATM) editions of Horstman & Cornell's "Core Java" Vol 1+2. I was pretty impressed, and was wondering if anyone thinks the latest ones would be worth a purchase - or if they are considered pretty good?

I am after the type of book that isn't a "this is how to program", but more of a tour of the libraries and the correct Java way of doing things.

Thanks in advance.

Twitchy
May 27, 2005

ssergE posted:

Hello All,

I am just about to start on some Java projects again, and was wondering what a good book would be for somebody with strong programming knowledge. I am after something akin to the classic K&R C book, but for Java. It should cover Java 1.6.

I own the 6th (I think - they are in storage ATM) editions of Horstman & Cornell's "Core Java" Vol 1+2. I was pretty impressed, and was wondering if anyone thinks the latest ones would be worth a purchase - or if they are considered pretty good?

I am after the type of book that isn't a "this is how to program", but more of a tour of the libraries and the correct Java way of doing things.

Thanks in advance.

The 2nd edition of Effective Java by Joshua Bloch is out, you might want to check that out. It doesn't neccesserally go in depth into the API's but it will give you a greater knowledge of how to use Java, as it happens, effectively.

Twitchy fucked around with this message at 11:58 on Jun 2, 2008

Twitchy
May 27, 2005

shodanjr_gr posted:

I am writting a small desktop search app. Im getting my results fine and dandy, and what i am trying to do, is launch my results, through my GUI. So if i get a .doc as a result, i wanna be able to launch whatever app my user has associated with .doc files (be it openoffice, ms word or wordpad). I also want to be able to do an "open containing folder" operation for each of my results.


The way you worded your previous reply, i got the impression that you have to know beforehand what programs are used for each filetype, and then issue a command-line call for those programs (passing the file to be opened as a parameter), which would make an application impossible to develop, considering the limitless combinations of file types and applications.



edit:

Found what i needed

code:
Runtime run = Runtime.getRuntime();
Process p = run.exec("cmd.exe /C "+this.my_file.getCanonicalPath());
This does what i want exactly wanted (with a drawback of the spawned application instances being child instances to the original java app...so the app doesnt completely shutdown until the children are closed...any way to get around that?).

http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/

How about this using this API? I haven't tried it myself but it does say:

quote:

Specifically, the new Desktop API allows your Java applications to do the following:

Launch the host system's default browser with a specific Uniform Resource Identifier (URI)

Launch the host system's default email client

Launch applications to open, edit, or print files associated with those applications

Edit: Just tested and it worked fine for both .doc and .jpg, so you might want to check it out considering it should be platform independent and it's not a child of the Java application.

code:
Desktop d = Desktop.getDesktop();

try {
    d.edit(new File("Untitled.jpg"));
} catch (IOException ex) {
    // exception
}

Twitchy fucked around with this message at 12:20 on Jun 2, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm trying to initiate a file download after a POST to a servlet, but it doesn't seem to work. What am I doing wrong? Almost the exact same code works for initiating a download from a GET request, just not for a POST. The only difference I see in firebug is Transfer-Encoding chunked. Do I need to set the content length?

response is my HttpServletResponse object.

code:
byte[] data = Base64Coder.decode(image.getBytes());
response.setContentType("image/jpeg");
response.setHeader("Content-disposition", "attachment; filename=\"something.jpg\"");
response.getOutputStream().write(data);
response.getOutputStream().close();

fletcher fucked around with this message at 01:57 on Jun 3, 2008

shodanjr_gr
Nov 20, 2007
How can i detect when a JFrame closes "for good".

I know about the WindowListener adn looking for a Window_closing event. Thing is, i want my app's defaultOnCloseOperation to be HIDE_ON_CLOSE, but i want to be able to catch the event when the app "shuts down" and do some finalization stuff...

Ideas?

1337JiveTurkey
Feb 17, 2005

shodanjr_gr posted:

How can i detect when a JFrame closes "for good".

I know about the WindowListener adn looking for a Window_closing event. Thing is, i want my app's defaultOnCloseOperation to be HIDE_ON_CLOSE, but i want to be able to catch the event when the app "shuts down" and do some finalization stuff...

Ideas?

If you want closing that window to end the application, then you want the default operation to be DISPOSE_ON_CLOSE. HIDE_ON_CLOSE is for when you foresee yourself showing it again in the near future and don't want to incur the expense of disposing one window and creating a new one a short time later. If you want it only sometimes to close the application and other times not to, then I'd suggest reconsidering that aspect since it will be quite confusing to users for their program to only sometimes shut down when they close the window.

shodanjr_gr
Nov 20, 2007

1337JiveTurkey posted:

If you want closing that window to end the application, then you want the default operation to be DISPOSE_ON_CLOSE. HIDE_ON_CLOSE is for when you foresee yourself showing it again in the near future and don't want to incur the expense of disposing one window and creating a new one a short time later. If you want it only sometimes to close the application and other times not to, then I'd suggest reconsidering that aspect since it will be quite confusing to users for their program to only sometimes shut down when they close the window.

I want X to hide my app since i got a taskbar icon running that the user can click to re-display the app. Think how an IM app works, where clicking the X button on the window doesnt close the app, it just hides it.

Thing is, when the user closes the app (such as when right clicking on the taskbar icon and clicking exit, or when going to file -> close), i want to run some finalization stuff. The obvious way is to go and do the finalization stuff inside the handler of every Event that leads to application shutdown, but i am wondering if there is a more "generic" way to do it.

epswing
Nov 4, 2003

Soiled Meat

shodanjr_gr posted:

..but i am wondering if there is a more "generic" way to do it.

There is, you probably want a shutdown hook. Here's how I usually do it:

code:
public class YourMainClass {
	public YourMainClass() {
		Runtime.getRuntime().addShutdownHook(new ShutdownHook(this));
	}
}

class ShutdownHook extends Thread {
	YourMainClass prog;
	public ShutdownHook(YourMainClass prog) {
		this.prog = prog;
	}
	public void run() {
		System.out.println("Shutting down...");
		prog.closeThingy();
		prog.disconnectStuff();
		prog.turnOffLights();
		System.out.println("Bye!");
	}
}

Adbot
ADBOT LOVES YOU

shodanjr_gr
Nov 20, 2007
epswing, you're da man!

Cheers :)

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply