Pobieranie prezentacji. Proszę czekać

Pobieranie prezentacji. Proszę czekać

Wykład 8 (fragmenty) © 2009 Java Programowanie w środowiskach graficznych.

Podobne prezentacje


Prezentacja na temat: "Wykład 8 (fragmenty) © 2009 Java Programowanie w środowiskach graficznych."— Zapis prezentacji:

1 Wykład 8 (fragmenty) © 2009 Java Programowanie w środowiskach graficznych

2 2 HTML i Swing Komponenty swinga są w stanie interpretować większość znaczników HTML łącznie z takimi jak IMG import javax.swing.*; public class HTMLLabelApplet extends JApplet { public void init( ) { JLabel theText = new JLabel( " Hello! This is a multiline label with bold " + "and italic text. " + "It can use paragraphs, horizontal lines, " + " colors " + "and most of the other basic features of HTML 3.2 "); this.getContentPane( ).add(theText); }

3 3 JEditorPane Klasa zapewnia szerokie możliwości renderowania elementów HTML, takich jak ramki, formularze, odsyłacze, CSS, RTF Użycie klasy wymaga podania jako parametru konstruktora Stringu w postaci HTML public JEditorPane( ) public JEditorPane(URL initialPage) throws IOException public JEditorPane(String url) throws IOException public JEditorPane(String mimeType, String text) public void setPage(URL page) throws IOException public void setPage(String url) throws IOException public void setText(String html) Inicjalizacja obiektu później

4 4 Przykład – przeglądarka WWW public static void main(String[] args) { JEditorPane jep = new JEditorPane( ); jep.setEditable(false); try { jep.setPage("http://www.kis.p.lodz.pl"); } catch (IOException e) { jep.setContentType("text/html"); jep.setText(" Could not load http://www.kis.p.lodz.pl "); } JScrollPane scrollPane = new JScrollPane(jep); JFrame f = new JFrame("O'Reilly & Associates"); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setContentPane(scrollPane); f.setSize(512, 342); f.show( ); }

5 5 Przykład – przeglądarka WWW

6 6 Przykład – ciąg Fibonacciego StringBuffer result = new StringBuffer(" Fibonacci Sequence "); long f1 = 0; long f2 = 1; for (int i = 0; i < 50; i++) { result.append(" "); result.append(f1); long temp = f2; f2 = f1 + f2; f1 = temp; } result.append(" "); JEditorPane jep = new JEditorPane("text/html",result.toString( )); jep.setEditable(false); JScrollPane scrollPane = new JScrollPane(jep); JFrame f = new JFrame("Fibonacci Sequence"); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setContentPane(scrollPane);

7 7 Obsługa hiperłączy Kliknięcie hiperlinku na na oknie JEditorPane uruchamia zdarzenie Nazwa zdarzenia HyperlinkListener javax.swing.event.HyperlinkListener public void hyperlinkUpdate(HyperlinkEvent e) Obiekt HyperlinkEvent zawiera w sobie metodę getURL(), która pozwala obsłużyć wskazywany adres HyperlinkEvent Obiekt nasłuchu Nazwa interfejsu Implementowana metoda

8 8 Obsługa hiperłączy public HyperlinkEvent.EventType getEventType( ) Uwaga: zdarzenie hyperlinkUpdate następuje przy każdym ruchu myszy nad hiperłączem HyperlinkEvent.EventType.EXITED HyperlinkEvent.EventTypeENTERED HyperlinkEvent.EventType.ACTIVATED Nazwa funkcji: Zwracane wartości:

9 9 Obsługa hiperłączy import javax.swing.*; import javax.swing.event.*; public class LinkFollower implements HyperlinkListener { private JEditorPane pane; public LinkFollower(JEditorPane pane) { this.pane = pane; } public void hyperlinkUpdate(HyperlinkEvent evt) { if (evt.getEventType()==HyperlinkEvent.EventType.ACTIVATED) { try { pane.setPage(evt.getURL( )); } catch (Exception e) {} } Przykład: SimpleWebBrowser

10 10 Dostęp do źródła HTML Parametry funkcji: strumień z którego czytany jest kod HTML oraz instancja obiektu javax.swing.text.html.HTMLDocument Klasa JEdiorPane w założeniu sama przetwarza plik HTML. Istnieje jednak metoda: public void read(InputStream in, Object document) throws IOException Umożliwiająca czytanie źródła HTML Kiedy się przydaje: Strumień jest przekazywany przez klasę filtrującą, np. dla dekompresji ZIP. Wymagana jest akcja przed wyświetleniem strony, np. autoryzacja na serwerze

11 11 Dostęp do źródła HTML try { URL u = new URL("http://www.kis.p.lodz.pl"); InputStream in = u.openStream( ); jep.read(in, doc); } catch (IOException e) { System.err.println(e); } JEditorPane jep = new JEditorPane( ); jep.setEditable(false); EditorKit htmlKit = ep.getEditorKitForContentType("text/html"); HTMLDocument doc = (HTMLDocument)htmlKit.createDefaultDocument( ); jep.setEditorKit(htmlKit); JScrollPane scrollPane = new JScrollPane(jep); JFrame f = new JFrame(KIS"); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setContentPane(scrollPane); f.setSize(640, 480); f.show( );

12 12 Parsowanie źródła HTML automatyczne pobieranie fragmentu strony WWW zawierającej istotne dane rekurencyjne podążanie za hiperłączami wyszukiwanie informacji Kiedy jest potrzebne? Brak ścisłej kontroli składni Możliwość błędów hiperłączy Dlaczego parsowanie HTML jest trudne? Co udostępnia JAVA? javax.swing.text.html javax.swing.text.html.parser biblioteka nie jest dostatecznie udokumentowana konstruktory obiektów często nie są publiczne obiekty zawierają klasy wewnętrzne

13 13 Klasa HTMLEditorKit.Parser Klasa wewnętrzna javax.swing.html.HTMLEditorKit public abstract static class HTMLEditorKit.Parser extends Object Przetwarzanie zaimplementowano w klasie pochodnej public class ParserDelegator extends HTMLEditorKit.Parser Początek znacznika Koniec znacznika Puste znaczniki Tekst Komentarze. Obiekt tej klasy odczytuje ze strumienia Reader. Poszukiwane są następujące fragmenty tekstu:

14 14 Klasa HTMLEditorKit.Parser … W przypadku znalezienia odpowiedniego fragmentu wywoływana jest odpowiednia metoda z obiektu klasy dziedziczącej z: javax.swing.text.html.HTMLEditorKit.ParserCallback … zdefiniowaną klasę pochodną przekazujemy do obiektu parsera w funkcji: public void parse(Reader in, HTMLEditorKit.ParserCallback callback, boolean ignoreCharacterSet) throws IOException Uwaga: parsowanie odbywa się w osobnym wątku

15 15 Uzyskiwanie obiektu ParserDelegator import javax.swing.text.html.*; public class ParserGetter extends HTMLEditorKit { public HTMLEditorKit.Parser getParser( ) { return super.getParser( ); } Funkcja getParser zwraca obiekt ParserDelegator. Utworzenie obiektu w normalny sposób jest trudne, ponieważ wymaga zdefiniowania DTD (SGML document type definition)

16 16 Tworzenie funkcji zwrotnych public static class HTMLEditorKit.ParserCallback extends Object Utworzenie klasy pochodnej polega na przeciążeniu wybranych metod obsługujących zdarzenia: public void handleText(char[] text, int position) public void handleComment(char[] text, int position) public void handleStartTag(HTML.Tag tag,MutableAttributeSet attributes, int position) public void handleEndTag(HTML.Tag tag, int position) public void handleSimpleTag(HTML.Tag tag,MutableAttributeSet attributes, int position) public void handleError(String errorMessage, int position) Istnieje dodatkowo metoda public void flush( ) throws BadLocationException wykonywana na zakończenie parsowania

17 17 Przykład – filtrowanie tekstu import javax.swing.text.html.*; import java.io.*; public class TagStripper extends HTMLEditorKit.ParserCallback { private Writer out; public TagStripper(Writer out) { this.out = out; } public void handleText(char[] text, int position) { try { out.write(text); out.flush( ); } catch (IOException e) { System.err.println(e); }

18 18 Przykład – filtrowanie tekstu Kroki użycia klasy TagStripper 1. Utworzenie obiektu parsera ParserGetter kit = new ParserGetter( ); HTMLEditorKit.Parser parser = kit.getParser( ); 2. Utworzenie obiektu klasy TagStripper HTMLEditorKit.ParserCallback callback = new TagStripper(new OutputStreamWriter(System.out)); 3. Otwarcie strumienia wejściowego pliku HTML URL u = new URL("http://www.kis.p.lodz.pl"); InputStream in = new BufferedInputStream(u.openStream( )); InputStreamReader r = new InputStreamReader(in); 4. Parsowanie właściwe parser.parse(r, callback, false);

19 19 Klasa HTML.Tag public static class HTML.Tag extends Object public String toString( ) Zaimplementowane metody: Zwraca prawdę, jeśli znacznik powoduje złamanie linii (pojedyncze) Zwraca prawdę, jeśli znacznik powoduje zamknięcie akapitu – podwójne złamanie linii Zwraca prawdę, jeśli znacznik powoduje zachowanie typów i ilości znaków białych Klasa pozwala wydobyć z HTML tekst wraz z zachowaniem akapitów public boolean breaksFlow( ) public boolean isBlock( ) public boolean isPreformatted( )

20 20 Klasa HTML.Tag Ulepszony TagStripper - inicjalizacja import javax.swing.text.*; import javax.swing.text.html.*; import javax.swing.text.html.parser.*; import java.io.*; import java.net.*; public class LineBreakingTagStripper extends HTMLEditorKit.ParserCallback { private Writer out; private String lineSeparator; public LineBreakingTagStripper(Writer out) { this(out, System.getProperty("line.separator", "\r\n")); } public LineBreakingTagStripper(Writer out, String lineSeparator) { this.out = out; this.lineSeparator = lineSeparator; }

21 21 Klasa HTML.Tag Ulepszony TagStripper – funkcje zwrotne public void handleText(char[] text, int position) { try { out.write(text); out.flush( ); } catch (IOException e) {System.err.println(e);} } public void handleEndTag(HTML.Tag tag, int position) { try { if (tag.isBlock( )) { out.write(lineSeparator); } else if (tag.breaksFlow( )) { out.write(lineSeparator); } catch (IOException e) {System.err.println(e);} }

22 22 Klasa HTML.Tag Ulepszony TagStripper – funkcje zwrotne public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes, int position) { try { if (tag.isBlock( )){ out.write(lineSeparator); } else if (tag.breaksFlow( )) { out.write(lineSeparator); } else { out.write(' '); } catch (IOException e) {System.err.println(e);} }

23 23 HTML.Tag – znaczniki HTML.Tag.A HTML.Tag.FRAMESET HTML.Tag.PARAM HTML.Tag.ADDRESS HTML.Tag.H1 HTML.Tag.PRE HTML.Tag.APPLET HTML.Tag.H2 HTML.Tag.SAMP HTML.Tag.AREA HTML.Tag.H3 HTML.Tag.SCRIPT HTML.Tag.B HTML.Tag.H4 HTML.Tag.SELECT HTML.Tag.BASE HTML.Tag.H5 HTML.Tag.SMALL HTML.Tag.BASEFONT HTML.Tag.H6 HTML.Tag.STRIKE HTML.Tag.BIG HTML.Tag.HEAD HTML.Tag.DFN HTML.Tag.LINK HTML.Tag.TR HTML.Tag.DIR HTML.Tag.MAP HTML.Tag.TT HTML.Tag.DIV HTML.Tag.MENU HTML.Tag.U HTML.Tag.DL HTML.Tag.META HTML.Tag.UL HTML.Tag.DT HTML.Tag.NOFRAMES HTML.Tag.VAR HTML.Tag.EM HTML.Tag.OBJECT HTML.Tag.IMPLIED HTML.Tag.FONT HTML.Tag.OL HTML.Tag.COMMENT HTML.Tag.FORM HTML.Tag.OPTION HTML.Tag.FRAME HTML.Tag.PHTML.Tag.TH HTML.Tag.LI HTML.Tag.BLOCKQUOTE HTML.Tag.HR HTML.Tag.STRONG HTML.Tag.BODY HTML.Tag.HTML HTML.Tag.STYLE HTML.Tag.BR HTML.Tag.I HTML.Tag.SUB HTML.Tag.CAPTION HTML.Tag.IMG HTML.Tag.SUP HTML.Tag.CENTER HTML.Tag.INPUT HTML.Tag.TABLE HTML.Tag.CITE HTML.Tag.ISINDEX HTML.Tag.TD HTML.Tag.CODE HTML.Tag.KBD HTML.Tag.TEXTAREA HTML.Tag.DD HTML.Tag.S if(tag==HTML.Tag.H1) …

24 24 HTML.Tag – atrybuty public void handleStartTag(HTML.Tag tag,MutableAttributeSet attributes, int position) public void handleSimpleTag(HTML.Tag tag,MutableAttributeSet attributes, int position) public int getAttributeCount( ) public boolean isDefined(Object name) public boolean containsAttribute(Object name, Object value) public boolean containsAttributes(AttributeSet attributes) public boolean isEqual(AttributeSet attributes) public AttributeSet copyAttributes( ) public Enumeration getAttributeNames( ) public Object getAttribute(Object name) public AttributeSet getResolveParent( ) public abstract interface MutableAttributeSet extends AttributeSet value jest najczęściej klasy String vame jest klasy javax.swing.text.html.HTML.Attribute Dla AttributeSet i MutableAttributeSet

25 25 HTML.Tag – atrybuty HTML.Attribute.ACTION HTML.Attribute.ALIGN HTML.Attribute.ALINK HTML.Attribute.ALT HTML.Attribute.ARCHIVE HTML.Attribute.BACKGROUND HTML.Attribute.BGCOLOR HTML.Attribute.BORDER HTML.Attribute.CELLPADDING HTML.Attribute.CELLSPACING HTML.Attribute.CHECKED HTML.Attribute.CLASS HTML.Attribute.CLASSID HTML.Attribute.CLEAR HTML.Attribute.CODE HTML.Attribute.CODEBASE HTML.Attribute.CODETYPE HTML.Attribute.COLOR HTML.Attribute.COLS HTML.Attribute.COLSPAN HTML.Attribute.COMMENT HTML.Attribute.COMPACT HTML.Attribute.CONTENT HTML.Attribute.COORDS HTML.Attribute.DATA HTML.Attribute.DECLARE HTML.Attribute.DIR HTML.Attribute.DUMMY HTML.Attribute.ENCTYPE HTML.Attribute.ENDTAG HTML.Attribute.FACE HTML.Attribute.FRAMEBORDER HTML.Attribute.HALIGN HTML.Attribute.HEIGHT HTML.Attribute.HREF HTML.Attribute.HSPACE HTML.Attribute.HTTPEQUIV HTML.Attribute.ID HTML.Attribute.ISMAP HTML.Attribute.LANG HTML.Attribute.LANGUAGE HTML.Attribute.LINK HTML.Attribute.LOWSRC HTML.Attribute.MARGINHEIGHT HTML.Attribute.MARGINWIDTH HTML.Attribute.MAXLENGTH HTML.Attribute.METHOD HTML.Attribute.MULTIPLE HTML.Attribute.N HTML.Attribute.NAME HTML.Attribute.NHREF HTML.Attribute.NORESIZE HTML.Attribute.NOSHADE HTML.Attribute.NOWRAP HTML.Attribute.PROMPT HTML.Attribute.REL HTML.Attribute.REV HTML.Attribute.ROWS HTML.Attribute.ROWSPAN HTML.Attribute.SCROLLING HTML.Attribute.SELECTED HTML.Attribute.SHAPE HTML.Attribute.SHAPES HTML.Attribute.SIZE HTML.Attribute.SRC HTML.Attribute.STANDBY HTML.Attribute.START HTML.Attribute.STYLE HTML.Attribute.TARGET HTML.Attribute.TEXT HTML.Attribute.TITLE HTML.Attribute.TYPE HTML.Attribute.USEMAP HTML.Attribute.VALIGN HTML.Attribute.VALUE HTML.Attribute.VALUETYPE HTML.Attribute.VERSION HTML.Attribute.VLINK HTML.Attribute.VSPACE HTML.Attribute.WIDTH

26 26 HTML.Tag – atrybuty zmienne W interfejsie MutableAttributeSet zadeklarowano dodatkowe funkcje do zmiany atrybutów public void addAttribute(Object name, Object value) public void addAttributes(AttributeSet attributes) public void removeAttribute(Object name) public void removeAttributes(Enumeration names) public void removeAttributes(AttributeSet attributes) public void setResolveParent(AttributeSet parent)

27 27 HTML.Tag – atrybuty zmienne Przykład: pobierz plik HTML i zamień ścieżki we wszystkich znacznikach (A, IMG, itp.) na bezwzględne i zapisz plik. public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int position) { try { out.write("<" + tag); this.writeAttributes(attributes); out.write(">"); out.flush( ); } catch (IOException e) {System.err.println(e);} } Przetwarzanie początku znacznika

28 28 HTML.Tag – atrybuty zmienne public void handleEndTag(HTML.Tag tag, int position) { try { out.write(" "); out.flush( ); } catch (IOException e) { System.err.println(e); } Przetwarzanie końca znacznika

29 29 HTML.Tag – atrybuty zmienne public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes, int position) { try { out.write("<" + tag); this.writeAttributes(attributes); out.write(">"); } catch (IOException e) { System.err.println(e); } Przetwarzanie pojedynczego znacznika

30 30 HTML.Tag – atrybuty zmienne public void handleText(char[] text, int position) { try { out.write(text); out.flush( ); } catch (IOException e) {System.err.println(e);} } Przetwarzanie tekstu

31 31 HTML.Tag – atrybuty zmienne public void handleComment(char[] text, int position) { try { out.write("<!-- "); out.write(text); out.write(" -->"); out.flush( ); } catch (IOException e) {System.err.println(e);} } Przetwarzanie komentarza

32 32 HTML.Tag – atrybuty zmienne private void writeAttributes(AttributeSet attributes) throws IOException { Enumeration e = attributes.getAttributeNames( ); while (e.hasMoreElements( )) { Object name = e.nextElement( ); String value = (String) attributes.getAttribute(name); try { if(name==HTML.Attribute.HREF || name==HTML.Attribute.SRC || name==HTML.Attribute.LOWSRC ||name==HTML.Attribute.CODEBASE ) { URL u = new URL(base, value); out.write(" " + name + "=\"" + u + "\""); } else out.write(" " + name + "=\"" + value + "\""); } catch (MalformedURLException ex) { … } } Przetwarzanie atrybutów


Pobierz ppt "Wykład 8 (fragmenty) © 2009 Java Programowanie w środowiskach graficznych."

Podobne prezentacje


Reklamy Google