import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class FetchURLPane {
public static void main(String args[]) throws Exception {
int argc = args.length;
// Check for valid number of parameters
if (argc != 1) {
System.out.println ("Syntax :");
System.out.println ("java FetchURL url");
return;
}
// Catch any thrown exceptions
try {
// Create an instance of java.net.URL
java.net.URL myURL = new URL ( args[0] );
// Fetch the content, and read from an InputStream
InputStream in = myURL.openStream();
// creat and show HTML styled content in TextPane
showUI(in);
// Pause for user
System.out.println ();
System.out.println ("Hit enter to continue");
System.in.read();
System.exit(0);
} catch (MalformedURLException mue) {
System.err.println ("Unable to parse URL!");
return;
} catch (IOException ioe) {
System.err.println ("I/O Error : " + ioe);
return;
}
}
public static void showUI(InputStream in) {
// read data from inputstream
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
try {
line = br.readLine();
} catch (IOException e) {
// nothing is retrieved
System.out.println("Nothing is read.");
return;
}
int index1 = line.indexOf("<title>");
int index2 = line.indexOf("</title>");
String msg = line.substring(index1+7, index2);
JFrame frame = new JFrame(msg);
Container c = frame.getContentPane();
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// set style: normal
MutableAttributeSet normal = new SimpleAttributeSet();
// set style: center
MutableAttributeSet h1 = new SimpleAttributeSet();
StyleConstants.setAlignment(h1, StyleConstants.ALIGN_CENTER);
StyleConstants.setBold(h1, true);
// set style: italic
MutableAttributeSet italic = new SimpleAttributeSet();
StyleConstants.setItalic(italic, true);
// set style: bold
MutableAttributeSet bold = new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
index1 = line.indexOf("<h1>");
index2 = line.indexOf("</h1>");
msg = line.substring(index1+4, index2);
textPane.setText(msg + "\n");
doc.setParagraphAttributes(0, index2 - index1 - 4, h1, true);
// reset style
doc.setParagraphAttributes(index2-index1-3, 0, normal, true);
while(true) {
try {
line = br.readLine();
if(line != null) {
doc.insertString(doc.getLength(), line + "\n", null);
}
else
break;
} catch (Exception e) {}
}
JScrollPane scrollPane = new JScrollPane( textPane );
scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
c.add(scrollPane);
frame.setSize(500, 300);
frame.setVisible(true);
}
}