解答例 - 実習課題2 - 15.テキスト・コンポーネント2
(実習課題2)
実習課題1のプログラムを改良しなさい。
- リンクをクリックした際に、該当するページを表示できるようにする事。
- フレームで区切られたHTMLページにも対応できるようにする事。
- (ヒント)「hyperlinkUpdate」メソッドの引数「HyperlinkEvent」が「HTMLFrameHyperlinkEvent」オブジェクトであった場合、「HTMLDocument」クラスの「processHTMLFrameHyperlinkEvent」メソッドを呼び出す。
- (ヒント)「HTMLFrameHyperlinkEvent」オブジェクトであるかどうかの識別には「instanceof」を使用する。
- (ヒント)「HTMLDocument」オブジェクトの取得は「JEditorPane」の「getDocument」メソッドで。
- (ヒント)「JEditorPane」のAPIドキュメントを参考に。
解答例
/**
* HyperlinkSimpleBrowser.java
* TECHSCORE Javaユーザインタフェース15章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.ui.chapter15.exercise2;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
public class HyperlinkSimpleBrowser extends JFrame implements ActionListener, HyperlinkListener {
private JEditorPane editor;
private JTextField urlText;
public HyperlinkSimpleBrowser() {
super("HyperlinkSimpleBrowser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
//JTextField
urlText = new JTextField("http://");
urlText.setPreferredSize(new Dimension(600, 20));
urlText.addActionListener(this);
getContentPane().add(urlText, BorderLayout.NORTH);
//JEditorPane
editor = new JEditorPane();
editor.setEditable(false);
editor.addHyperlinkListener(this);
JScrollPane scroll = new JScrollPane(editor);
scroll.setPreferredSize(new Dimension(600, 400));
getContentPane().add(scroll);
pack();
}
public void actionPerformed(ActionEvent event) {
try {
editor.setPage(urlText.getText());
} catch (IOException ex) {
editor.setText("Error: " + ex.getMessage());
}
}
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() == (HyperlinkEvent.EventType.ACTIVATED)) {
urlText.setText(event.getURL().toString());
try {
if (event instanceof HTMLFrameHyperlinkEvent) {
HTMLDocument doc = (HTMLDocument) editor.getDocument();
doc.processHTMLFrameHyperlinkEvent(
(HTMLFrameHyperlinkEvent) event);
} else {
editor.setPage(event.getURL().toString());
}
} catch (IOException ex) {
editor.setText("Error : " + ex.getMessage());
}
}
}
public static void main(String[] args) {
new HyperlinkSimpleBrowser().setVisible(true);
}
}

