在编写java程序的时候,有时候需要把程序放到服务器上长时间运行,然而我们又很讨厌每次打开程序运行时一直弹出程序运行窗口在那里,为了解决这个问题,我们可以将我们的程序连接到一个“托盘”,当关闭程序时直接最小化到“托盘”,双击“托盘”就会还原程序运行窗口,只有右击“托盘”并点击“关闭”菜单才会真正退出程序。下面将介绍如何实现这个需求。

1.首先我们自定义一个类,该类继承自JFrame(extends JFrame),这样我们就创建了一个程序运行窗口,可以调用很多JFrame自带的窗口操作函数,如:setTitle()、setSize(700, 450)等。

2.实现上面自定义的类的构造函数:

首先,可以创建一个JTextArea和JPanel,这样可以在窗口下显示信息;

panel = new JPanel();  
textArea = new JTextArea();  
        panel.setLayout(new GridLayout());  
//      textArea.paintImmediately(textArea.getBounds());
         textArea.setLineWrap(true);//自动换行功能
         textArea.setWrapStyleWord(true);//断行不断字功能
         panel.add(new JScrollPane(textArea));   //当TextArea里的内容过长时生成滚动条


(当不断调用textArea.append()函数添加内容到textArea显示时,为了使得滚动条一直在下方显示

最新添加的内容,每调用一次textArea.append(),就需要调用一次 textArea.setCaretPosition(textArea.getText().length());)  

        add(panel);  

其次,实现托盘与程序的连接,我的代码为:

Image img = Toolkit.getDefaultToolkit().getImage(“E:/1.png”); //图片大小最好为16*16,网上可以下
TrayIcon trayIcon = new TrayIcon(img);
trayIcon.setToolTip(“托盘提示信息”);
trayIcon.setImageAutoSize(true);
SystemTray.getSystemTray().add(trayIcon);
PopupMenu pmenu = new PopupMenu(); //创建托盘右击时显示的菜单
MenuItem open = new MenuItem("打开");
open.addActionListener(new ActionListener() { //添加鼠标单击该菜单项时对应的操作事件
public void actionPerformed(ActionEvent e) {
setVisible(true);
}
});
pmenu.add(open);
MenuItem exit = new MenuItem("关闭");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pmenu.add(exit);
// 双击弹出窗体
trayIcon.addMouseListener(new MouseListener() { 鼠标双击托盘时对应的操作事件
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
setVisible(true);
}
}


public void mousePressed(MouseEvent e) {
}


public void mouseReleased(MouseEvent e) {
}


public void mouseEntered(MouseEvent e) {
}


public void mouseExited(MouseEvent e) {
}
});
trayIcon.setPopupMenu(pmenu);

最后,实现程序的其他功能;

程序编写完毕后,就可以运行了。这里也需要说一下:

一般运行时,我们喜欢打成jar包,然后编写.bat文件运行之,但这样就会弹出黑框,很烦人,怎么解决呢?

方法很简单,就是在.bat文件的同级目录下编写一个run.vbs文件,内容为:

Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c xxx.bat",vbhide

这样每次运行run.vbs文件,黑框就没有了!!