说明:
- 启动后会置顶出现一弹窗
- 弹窗为黑色
- 一直为黑色表明没有网络
- 黑红交替为有网络
- 鼠标点击可以移动图标
- 三击结束任务
生成的jar包
使用javaGUI编写检测是否有网 simplejava.jar
生成的exe文件
代码如下
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JLabel;
import javax.swing.JWindow;
import javax.swing.event.MouseInputListener;
/**
* 检测是否存在网络
*
* @author Jeby Sun
*/
public class MyFrame extends JWindow {
private static final long serialVersionUID = 1L;
JLabel titleLbl;
public MyFrame() throws IOException {
int waH = 50;
//设置背景颜色不能直接调用其setBackground方法,而要设置其ContentPane的背景颜色。
this.getContentPane().setBackground(Color.black);
this.setBounds(10, 10, waH, waH);
this.setLayout(null);
titleLbl = new JLabel();
titleLbl.setOpaque(true);
titleLbl.setBackground(Color.BLACK);
titleLbl.setBounds(0, 0, waH, waH);
this.add(titleLbl);
//鼠标事件处理类
MouseEventListener mouseListener = new MouseEventListener(this);
titleLbl.addMouseListener(mouseListener);
titleLbl.addMouseMotionListener(mouseListener);
this.setAlwaysOnTop(true);
this.setVisible(true);
Boolean flag = true;
while (true){
Process process = Runtime.getRuntime().exec("ping www.baidu.com");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream(), "GBK"));
String line = null;
while((line=bufferedReader.readLine()) != null) {
if (line!=null&&line.contains("的回复")){
flag = !flag;
if (flag){
titleLbl.setBackground(Color.RED);
}else {
titleLbl.setBackground(Color.BLACK);
}
}
}
flag = true;
titleLbl.setBackground(Color.BLACK);
}
}
/**
* 鼠标事件处理
*
* @author Jeby Sun
*/
class MouseEventListener implements MouseInputListener {
Point origin;
//鼠标拖拽想要移动的目标组件
MyFrame frame;
public MouseEventListener(MyFrame frame) {
this.frame = frame;
origin = new Point();
}
@Override
public void mouseClicked(MouseEvent e) {
int clickTimes = e.getClickCount();
if (clickTimes == 3) {
System.exit(0);
}
}
/**
* 记录鼠标按下时的点
*/
@Override
public void mousePressed(MouseEvent e) {
origin.x = e.getX();
origin.y = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
}
/**
* 鼠标移进标题栏时,设置鼠标图标为移动图标
*/
@Override
public void mouseEntered(MouseEvent e) {
this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
/**
* 鼠标移出标题栏时,设置鼠标图标为默认指针
*/
@Override
public void mouseExited(MouseEvent e) {
this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
/**
* 鼠标在标题栏拖拽时,设置窗口的坐标位置
* 窗口新的坐标位置 = 移动前坐标位置+(鼠标指针当前坐标-鼠标按下时指针的位置)
*/
@Override
public void mouseDragged(MouseEvent e) {
Point p = this.frame.getLocation();
this.frame.setLocation(
p.x + (e.getX() - origin.x),
p.y + (e.getY() - origin.y));
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
public static void main(String[] args) throws IOException {
new MyFrame();
}
}