package com.han;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class SystemTray_1 extends JFrame {

/**
*
*/
private static final long serialVersionUID = -2435953743688848219L;

private static SystemTray_1 frame;
private TrayIcon trayIcon = null;

public SystemTray_1() {
// TODO Auto-generated constructor stub

getContentPane().add(new JLabel("这是一个听歌程序界面", SwingConstants.CENTER));

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {

final JDialog dialog = new JDialog(frame, "确认对话框", true);
Container dialogContainer = dialog.getContentPane();
JLabel label = new JLabel("是否缩小到系统托盘?否,直接退出整个程序",
SwingConstants.CENTER);
label.setFont(new Font("宋体", Font.PLAIN, 12));
label.setForeground(Color.MAGENTA);
JCheckBox checkBox = new JCheckBox("以后不再提醒");
JButton buttonConfirm = new JButton("确定");
// String str = "<html> <font face= '宋体' size= '4' color= '#000000'><b>取消</b></font></html>";
String str = "取消";
JButton buttonCancel = new JButton(str);
buttonCancel.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 12));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
dialogContainer.add(label, BorderLayout.CENTER);
dialogContainer.add(panel, BorderLayout.SOUTH);
panel.add(checkBox);
panel.add(buttonConfirm);
panel.add(buttonCancel);
dialog.setSize(350, 150);

buttonConfirm.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("here");
if (SystemTray.isSupported()) {
SystemTray systemTray = SystemTray.getSystemTray();
if (trayIcon != null) {
systemTray.remove(trayIcon);
System.out.println("trayIcon removed");
}
URL resource = this.getClass().getResource(
"/images/Luxun.jpg");
BufferedImage imageScaled = null;
BufferedImage in;
try {
in = ImageIO.read(resource);
imageScaled = ImageScale.scale(in, 0.05, 0.05,
1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

PopupMenu popupMenu = new PopupMenu();
MenuItem item;
try {
item = new MenuItem(new String("Exit"
.getBytes("ISO-8859-1"), "GBK"));
MenuItem item2 = new MenuItem("open");
popupMenu.add(item);
popupMenu.add(item2);
item.addActionListener(new ActionListener() {

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

});

item2.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.setVisible(true);
}

});

} catch (HeadlessException
| UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

trayIcon = new TrayIcon(imageScaled,
"音乐程序系统托盘", popupMenu);
trayIcon.setImageAutoSize(true);

// For double clicks on tray icon in Windows
// System, the MouseListener and the ActionListener
// perform the same effect.
/*trayIcon.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
frame.setVisible(true);
}
}
});*/

trayIcon.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.setVisible(true);
}

});

try {
systemTray.add(trayIcon);
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dialog.dispose();
frame.setVisible(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,
"<html> <font face = '宋体' size = '4' color = '#FF00FF'>" +
" <b> 已经有程序在运行! </b> </font> </html>");*/
Object[] options = { "确定" };
JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);

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);*/
}

}