Skip to content

Instantly share code, notes, and snippets.

@lehnerpat
Created October 4, 2012 10:28
Show Gist options
  • Save lehnerpat/3832780 to your computer and use it in GitHub Desktop.
Save lehnerpat/3832780 to your computer and use it in GitHub Desktop.
xkcd.java
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class xkcd extends JFrame {
private static final String XKCD_URL = "http://dynamic.xkcd.com/random/comic/";
private JLabel comic;
public static void main(String[] args)
{
xkcd win = new xkcd();
win.setVisible(true);
win.feedNewPic();
}
public xkcd()
{
super("xkcd comic feed");
/* todo - make it resize dynamically */
setSize(850, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/* setup the comic */
comic = makeComicLabel();
add(comic);
}
private void feedNewPic()
{
URL url;
Image image;
try {
url = new URL(getRandPic());
image = ImageIO.read(url);
comic.setIcon(new ImageIcon(image));
}
catch (Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR!");
}
}
private String getRandPic()
{
try
{
BufferedReader in = new BufferedReader(
new InputStreamReader(
new URL(XKCD_URL).openStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = in.readLine()) != null)
{
sb.append(line);
}
Matcher m = Pattern.compile("^.*<div id=\"comic\">\w*<img src=\"([^\"]+)\".*").matcher(sb.toString());
if (m.matches()) {
return m.group(1);
}
}
catch (MalformedURLException e){
e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();}
/* we shouldn't get here */
return "";
}
private JLabel makeComicLabel()
{
JLabel temp = new JLabel();
temp.addMouseListener(
new MouseListener()
{
public void mouseClicked(MouseEvent e)
{
feedNewPic();
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
);
return temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment