Communication between proccesses,Serialization
I wrote a java application,wrapped in a executable .jar file.I want user to click the .jar file to run the program, and click the "close" icon to hide the program(JFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Once the user click the .jar File again, the program run at background will be apper on the desktop(not hide). Only one program instance is running everytime.
Have easy way to get it?.thank you.
I have an idea:
Once the user first click .jar file to run the program, one process get the lock of a file(.lock) and App windows(JFrame) is serialized into a file(.object). The user click the .jar file again, the other process try to get the lock of the same file(.lock), and then failed. The second Process deserialized the .object file and can get a JFrame object, the setVisible method will be invoke on the JFrame object. The JFrame will be apper again.But I have a little trouble: the JFrame has a JMenu.It's inner classJMenu$ActionChangeListener can't be serialized( java.io.NotSerializableException: javax.swing.JMenu$ActionChangedListener)
partial code:
public class ExApp extends JFrame implements Serializable
{
private static final long serialVersionUID = 1L;
private ExApp _instance;
public ExApp()
{
super("在逃人员数据转换程序");
_instance = this;
}
public void init()
{
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JDesktopPane desk = new JDesktopPane();
setContentPane(desk);
//decomment the line,java.io.NotSerializableException will be thrown//setJMenuBar(new MenuBar(desk));
}
public static void main(String[] args) throws Exception
{
if (isRun()) {
//e.setVisible(true);
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("c:\\aa.obj"));
ExApp e = (ExApp) objIn.readObject();
e._instance.setVisible(true);
//e.setVisible(true);
objIn.close();
} else {
ExApp e = new ExApp();
e.init();
System.out.println("Write:" + e._instance);
ObjectOutputStream objOut = new ObjectOutputStream(
new FileOutputStream("c:\\aa.obj"));
objOut.writeObject(e);
objOut.close();
e.setSize(500, 400);
e.setVisible(true);
}
}
private static boolean isRun() throws Exception
{
File lockFile = new File("config/lock");
if (!lockFile.exists()) {
lockFile.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");
FileChannel fc = raf.getChannel();
FileLock fileLock = fc.tryLock();
if (fileLock != null && fileLock.isValid()) {
return false;
} else {
return true;
}
}
}

