SystemTray_1 (三)

2014-11-24 08:12:21 · 作者: · 浏览: 2
ible(false);
} else {
JOptionPane.showMessageDialog(dialog, "系统不支持托盘功能",
"Message", JOptionPane.INFORMATION_MESSAGE);
dialog.dispose();
}

}

});

buttonCancel.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("here2");
System.exit(0);

}

});

dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

// The dialog will be validated prior to being made visible.
// so it is very important to place this phrase in the end.
// For example, if we place it before the button action listener
// code block, the button action listener will not be taken
// effect.
dialog.setVisible(true);

}
});
}

public static void makeSingle(String singleId) {
RandomAccessFile raf = null;
FileChannel channel = null;
FileLock lock = null;

try {
// 在临时文件夹创建一个临时文件,锁住这个文件用来保证应用程序只有一个实例被创建.
File sf = new File(System.getProperty("java.io.tmpdir") +
singleId + ".single");
sf.deleteOnExit();
sf.createNewFile();

raf = new RandomAccessFile(sf, "rw");
channel = raf.getChannel();
lock = channel.tryLock();

if (lock == null) {
// 如果没有得到锁,则程序退出.
// 没有必要手动释放锁和关闭流,当程序退出时,他们会被关闭的.
// Error is for a automatically stop of the program, while
// for Exception, you have to handle it in the catch clause.
JOptionPane.showMessageDialog(null,
"An instance of the application is running.");
throw new Error("An instance of the application is running.");
}
} catch (Exception e) {
e.printStackTrace();
// System.exit(0);
}
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SystemTray_1.makeSingle("single.test"); // 保证程序只有一个实例在运行.
frame = new SystemTray_1();
frame.setTitle("这是一个听歌程序");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(400, 200);
/*System.out.println(frame.getExtendedState());
frame.setExtendedState(Frame.MAXIMIZED_BOTH);*/
}

}


摘自 Gaowen_HAN的专栏