图形用户界面:通过ip获取地址并显示天气情况

1.贴图展示


2.代码

Window.java
package com.xiang;

import java.applet.AudioClip;
import java.net.URL;
import javax.swing.JApplet;


public class Window {
	private Home home;
	private boolean isPlayMusic = false;
	private AudioClip audio;
	
	public Window() {
		final Window main = this;
		new Thread(new Runnable(){
            public void run() {
                home = new Home(main);
                home.setVisible(true);
            }
        }).start();
		
		URL audioPath = this.getClass().getResource("/music/baby.wav");//获取的是URL文本路径 调用 .getPath()获取类的绝对路径
        audio = JApplet.newAudioClip(audioPath);  
        audio.loop();  
        isPlayMusic = true;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Window();
	}
	public AudioClip getAudio() {
        return audio;
    }

    public void setAudio(AudioClip audio) {
        this.audio = audio;
    }

    public Home getHome() {
        return home;
    }

    public void setHome(Home home) {
        this.home = home;
    }

    public boolean isIsPlayMusic() {
        return isPlayMusic;
    }

    public void setIsPlayMusic(boolean isPlayMusic) {
        this.isPlayMusic = isPlayMusic;
    }
}

Home.java
package com.xiang;

import java.awt.Dimension;
import java.awt.Label;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.sun.awt.AWTUtilities;

public class Home extends JFrame implements ActionListener,
		MouseMotionListener, MouseListener {
	private JPanel panel;
	private JButton musicButton;
	private JButton closeButton;
	private JComboBox select;
	private JLabel weatherJLabel;
	//private JLabel weather[] = new JLabel[5];
	private Window main;
	private int rx;
	private int ry;

	public Home(Window main) {
		this.main = main;
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		this.setSize(650, 600);
		panel = new MyPanel("/photo/bg1.gif");
		panel.setSize(650, 600);
		panel.setLayout(null);

		musicButton = new MyButton("/photo/music.gif");
		musicButton.setBounds(240, 150, 60, 30);
		musicButton.addActionListener(this);
		
		/*String []strings ={"今天", "明天", "后天"};
		select = new JComboBox(strings);
		select.setBounds(310, 150, 60, 30);*/
		//System.out.println(select.getSelectedItem());
		//select.addActionListener(this);
		
		closeButton = new MyButton("/photo/close.gif");
		closeButton.setBounds(490, 150, 30, 30);
		closeButton.addActionListener(this);

		/*String weatherString = GetPlaceByIp.getweather();
		String[] weatherarray = new String[5];
		weatherarray = weatherString.split(",");
		for (int i = 0; i < weatherarray.length; i++) {
			weather[i] = new JLabel(weatherarray[i]);
			//System.out.println(weatherarray[i]);
			weather[i].setBounds(240, 300 + i * 15, 240, 30);
		}*/
		weatherJLabel = new MyLabel();
		weatherJLabel.setSize(340, 240);
		weatherJLabel.setBounds(230, 190, 340, 240);
		
		panel.add(musicButton);
		//panel.add(select);
		/*for (int i = 0; i < weatherarray.length; i++)
			panel.add(weather[i]);*/
		panel.add(closeButton);
		panel.add(weatherJLabel);

		this.addMouseListener(this);
		this.addMouseMotionListener(this);

		this.setContentPane(panel);
		this.setLocation(((int) screenSize.getWidth() - 600) / 2,
				((int) screenSize.getHeight() - 600) / 2);
		this.setUndecorated(true);
		AWTUtilities.setWindowOpaque(this, false);
		this.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == musicButton) {
			if (main.isIsPlayMusic()) {
				main.getAudio().stop();
				main.setIsPlayMusic(false);

			} else {
				main.getAudio().loop();
				main.setIsPlayMusic(true);
			}
		}
		else if(e.getSource() == closeButton)
		{
			//this.setVisible(false);
			System.exit(0);
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub
		this.setLocation(e.getXOnScreen() - rx, e.getYOnScreen() - ry);
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		rx = e.getX();
		ry = e.getY();
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}

}

GetPlaceByIp.java
package com.xiang;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

public class GetPlaceByIp {
	public static String getAddressByIP() {
		String province = null;
		String city = null;
		try {
			String strIP = getWebIp();
			URL url = new URL("http://ip.qq.com/cgi-bin/searchip?searchip1="+ strIP);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "GBK"));
			String line = null;
			StringBuffer result = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
			reader.close();
			strIP = result.substring(result.indexOf("该IP所在地为:"));
			strIP = strIP.substring(strIP.indexOf(":") + 1);
			province = strIP.substring(6, strIP.indexOf("省"));
			city = strIP.substring(strIP.indexOf("省") + 1, strIP
					.indexOf("市"));
			//System.out.print(city);
		} catch (IOException e) {
			return "读取失败";
		}
		return city;
	}

	/*public static void main(String[] args) throws Exception {
		String city = getAddressByIP();
		String cityString = null;
		try {
			cityString = URLEncoder.encode(city, "GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String link = "http://php.weather.sina.com.cn/xml.php?city="+cityString+"&password=DJOYnieT8234jlsK&day=0";

		URL url;

		try {
			url = new URL(link);
			Weather parser = new Weather(url);
			String[] nodes = { "city", "status1", "temperature1", "status2",
					"temperature2" };
			Map<String, String> map = parser.getValue(nodes);
			System.out.println(map.get(nodes[0]) + " 今天白天:" + map.get(nodes[1])
					+ " 最高温度:" + map.get(nodes[2]) + "℃ 今天夜间:"
					+ map.get(nodes[3]) + " 最低温度:" + map.get(nodes[4]) + "℃ ");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}*/

	public static String getWebIp() throws IOException {
		InputStream ins = null;  
        try {  
            URL url = new URL("http://1111.ip138.com/ic.asp");  
            URLConnection con = url.openConnection();  
            ins = con.getInputStream();  
            InputStreamReader isReader = new InputStreamReader(ins, "GB2312");  
            BufferedReader bReader = new BufferedReader(isReader);  
            StringBuffer webContent = new StringBuffer();  
            String str = null;  
            while ((str = bReader.readLine()) != null) {  
                webContent.append(str);  
                //System.out.println(str);
            }  
            int start = webContent.indexOf("[") + 1;
            int end = webContent.indexOf("]");
            return webContent.substring(start, end);
        } finally {
            if (ins != null) {
                ins.close();  
            }  
        }  
	}
	public static String getweather()
	{
		String city = getAddressByIP();
		String cityString = null;
		try {
			cityString = URLEncoder.encode(city, "GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String link = "http://php.weather.sina.com.cn/xml.php?city="+cityString+"&password=DJOYnieT8234jlsK&day=0";

		URL url;

		try {
			url = new URL(link);
			Weather parser = new Weather(url);
			String[] nodes = { "city", "status1", "temperature1", "direction1",
					"power1", "status2", "temperature2", "direction2", "power2", "chy_shuoming", "gm_s", "yd_s", };
			Map<String, String> map = parser.getValue(nodes);
			/*System.out.println(map.get(nodes[0]) + " 今天白天:" + map.get(nodes[1])
					+ " 最高温度:" + map.get(nodes[2]) + "℃ 今天夜间:"
					+ map.get(nodes[3]) + " 最低温度:" + map.get(nodes[4]) + "℃ ");*/
			return map.get(nodes[0]) + ",今天白天:" + map.get(nodes[1])
			+ ",温度:" + map.get(nodes[2]) + "℃,风向:" + map.get(nodes[3])
			+ ",风级:" + map.get(nodes[4]) + ",今天夜间:" + map.get(nodes[5])
			+ ",温度:" + map.get(nodes[6]) + "℃,风向:" + map.get(nodes[7])
			+ ",风级:" + map.get(nodes[8]) + ",穿衣说明:," + map.get(nodes[9]) + ",感冒说明:," + map.get(nodes[10])
			+ ",运动说明:," + map.get(nodes[11]);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return "";
	}
}

Weather.java
package com.xiang;

/**
 * java获取新浪天气预报代码
 */
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 解析xml文档,包括本地文档和url
 * 
 */
public class Weather {

	InputStream inStream;

	Element root;

	public InputStream getInStream() {

		return inStream;

	}

	public void setInStream(InputStream inStream) {

		this.inStream = inStream;

	}

	public Element getRoot() {

		return root;

	}

	public void setRoot(Element root) {

		this.root = root;

	}

	public Weather() {

	}

	/**
	 * 通过输入流来获取新浪接口信息
	 * 
	 * @param inStream
	 */
	public Weather(InputStream inStream) {

		if (inStream != null) {

			this.inStream = inStream;

			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();

			try {

				DocumentBuilder domBuilder = domfac.newDocumentBuilder();

				Document doc = domBuilder.parse(inStream);

				root = doc.getDocumentElement();

			} catch (ParserConfigurationException e) {

				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	public Weather(String path) {

		InputStream inStream = null;

		try {

			inStream = new FileInputStream(path);

		} catch (FileNotFoundException e1) {

			e1.printStackTrace();

		}

		if (inStream != null) {

			this.inStream = inStream;

			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();

			try {

				DocumentBuilder domBuilder = domfac.newDocumentBuilder();

				Document doc = domBuilder.parse(inStream);

				root = doc.getDocumentElement();

			} catch (ParserConfigurationException e) {

				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	public Weather(URL url) {

		InputStream inStream = null;

		try {

			inStream = url.openStream();

		} catch (IOException e1) {

			e1.printStackTrace();

		}

		if (inStream != null) {

			this.inStream = inStream;

			DocumentBuilderFactory domfac = DocumentBuilderFactory
					.newInstance();

			try {

				DocumentBuilder domBuilder = domfac.newDocumentBuilder();

				Document doc = domBuilder.parse(inStream);

				root = doc.getDocumentElement();

			} catch (ParserConfigurationException e) {

				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	/**
	 * 
	 * @param nodes
	 * @return 单个节点多个值以分号分隔
	 */
	public Map<String, String> getValue(String[] nodes) {

		if (inStream == null || root == null) {

			return null;

		}

		Map<String, String> map = new HashMap<String, String>();

		// 初始化每个节点的值为null
		for (int i = 0; i < nodes.length; i++) {

			map.put(nodes[i], null);

		}

		// 遍历第一节点
		NodeList topNodes = root.getChildNodes();

		if (topNodes != null) {

			for (int i = 0; i < topNodes.getLength(); i++) {

				Node book = topNodes.item(i);

				if (book.getNodeType() == Node.ELEMENT_NODE) {

					for (int j = 0; j < nodes.length; j++) {

						for (Node node = book.getFirstChild(); node != null; node = node
								.getNextSibling()) {

							if (node.getNodeType() == Node.ELEMENT_NODE) {

								if (node.getNodeName().equals(nodes[j])) {

									String val = node.getTextContent();

									String temp = map.get(nodes[j]);

									if (temp != null && !temp.equals("")) {

										temp = temp + ";" + val;

									} else {

										temp = val;

									}

									map.put(nodes[j], temp);

								}
							}
						}
					}
				}
			}
		}
		return map;
	}

	/*public static void main(String[] args) {
		String cityString = null;
		try {
			cityString = URLEncoder.encode("青岛", "GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String link = "http://php.weather.sina.com.cn/xml.php?city="+cityString+"&password=DJOYnieT8234jlsK&day=0";

		URL url;

		try {
			url = new URL(link);
			Weather parser = new Weather(url);
			String[] nodes = { "city", "status1", "temperature1", "status2",
					"temperature2" };
			Map<String, String> map = parser.getValue(nodes);
			System.out.println(map.get(nodes[0]) + " 今天白天:" + map.get(nodes[1])
					+ " 最高温度:" + map.get(nodes[2]) + "℃ 今天夜间:"
					+ map.get(nodes[3]) + " 最低温度:" + map.get(nodes[4]) + "℃ ");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}*/
}

MyPanel.java
package com.xiang;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JPanel;

public class MyPanel extends JPanel {
	private Image backImg;
	public MyPanel(String imgPath){
        backImg = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(imgPath));//Toolkit.getDefaultToolkit().getImage(...) 方法可接受 String 或者是 URL 参数,用以指定图像文件的路径。
        this.updateUI();
   }
    
    @Override
     public void paintComponent(Graphics g) {//插入背景图片
        super.paintComponent(g);
         if(backImg!=null)
             g.drawImage(backImg, 0, 0,this.getWidth(),this.getHeight(), null);
     }
}

MyButton.java
package com.xiang;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JButton;

public class MyButton extends JButton {
	private Image backImg;
	public MyButton(String imgPath){
        backImg = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(imgPath));
   }
	
	public void paintComponent(Graphics g) {//插入按钮背景
        super.paintComponent(g);
        if(backImg!=null)
            g.drawImage(backImg, 0, 0,this.getWidth(),this.getHeight(), null);
    }
}

MyLabel.java
package com.xiang;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;

public class MyLabel extends JLabel {

	private java.util.List<Message> msgs = new ArrayList<Message>();
	private String weatherString;
	private String[] weatherarray = new String[15];
	private int count;

	public MyLabel() {
		count = 0;
		weatherString = GetPlaceByIp.getweather().trim();
		weatherarray = weatherString.split(",");
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					// 显示信息内容
					repaint();
					try {
						Thread.sleep(1000);
					} catch (InterruptedException ex) {
						Logger.getLogger(MyLabel.class.getName()).log(
								Level.SEVERE, null, ex);
					}
				}
			}
		}).start();
	}

	public void paint(Graphics g) {
		createMsg();
		g.setColor(Color.red);
		for (Message msg : msgs) {
			g.drawString(msg.getMsg(), msg.getX(), msg.getY());
		}
	}

	private void createMsg() {
		// TODO Auto-generated method stub
		if (count >= weatherarray.length)
			count = 0;
		for (Message msg : msgs) {
			msg.setY(msg.getY() - 15);
		}
		if (msgs.size() > 0 && msgs.get(0).getY() < 0)
			msgs.remove(0);
		Message m = new Message((int) (120 - weatherarray[count].length() * 6),
				230, weatherarray[count]);
		// System.out.println(weatherarray[count]);
		msgs.add(m);
		count++;
	}
}

Message.java
package com.xiang;

public class Message {
	private int x;
    private int y;
    private String msg;

    public Message() {
    }

    
    public Message(int x, int y, String msg) {
        this.x = x;
        this.y = y;
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

3.目录结构


4.参考地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值