package com.czp;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.ServerSocket;
import javax.swing.JOptionPane;
import javax.swing.JWindow;
/***
* draw IP on screen
*
*
* @author CaoZhongping
*
*/
public class MyWindow extends JWindow {
private static final int FONT_SIZE = 26;
private final String FONT_NAME = "楷体";
private static final long serialVersionUID = 1L;
private ServerSocket sock;
private static Font font;
private int width;
public MyWindow(int width, int height) {
super();
font = new Font(FONT_NAME, Font.PLAIN, FONT_SIZE);
this.width = width;
this.setSize(width, height);
this.setPostion();
this.setAlwaysOnTop(true);
this.setVisible(true);
this.bindPort();
this.addMouseListener(new MyWinLister(this));
}
/**
* 单例运行
*/
private void bindPort() {
new Thread(new Runnable() {
@Override
public void run() {
try {
sock = new ServerSocket(6666);
sock.accept();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "GetIP Aready Running");
System.exit(0);
}
}
}).start();
}
public ServerSocket getSock() {
return sock;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString("Your IP is :" + getLocalIP() + " ", 0, this.getY()
+ FONT_SIZE);
}
private String getLocalIP() {
try {
return Inet4Address.getLocalHost().getHostAddress();
} catch (Exception e) {
return e.toString();
}
}
/**
* center to screen
*/
private void setPostion() {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((int) (d.getWidth() - this.width), 2);
}
/**
*
* double click quit
*
*/
class MyWinLister extends MouseAdapter {
private MyWindow window;
public MyWinLister(MyWindow window) {
super();
this.window = window;
}
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if (e.getClickCount() == 2) {
try {
this.window.getSock().close();
this.window.dispose();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
}
}
public static void main(String[] args) {
new MyWindow(320, 30);
}
}