LoginSignup
2
3

More than 5 years have passed since last update.

Java+Swingでヘルプダイアログを作る

Last updated at Posted at 2013-07-13

Java+Swingという標準機能でヘルプダイアログを作る方法です。
いわゆる普通のアプリを作る際に、ヘルプをHTMLで作っておき、そのHTMLをSwingでレンダリングさせます。

CSS3などを表示するのは普通に無理なので、この機能で表示するHTMLはあまり凝ったことをしないほうが良いです。

HelpDialog.java
import java.awt.Frame;
import java.io.IOException;
import java.net.URL;

import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.text.html.HTMLDocument;

/**
 * ヘルプダイアログ
 * @author tamura shingo
 *
 */
public class HelpDialog extends JDialog {
	
    private JScrollPane scrollPane;
    private JEditorPane html;
	
    /**
     * コンストラクタ
     * @param parent 親フレーム
     * @throws IOException ファイルオープンに失敗
     */
    public HelpDialog(Frame parent, URL url) throws IOException {
        super(parent, false);
        makeDialog(url);
    }
	
    /**
     * 指定したURLを開く。
     * @param url
     */
    private synchronized void open(URL url) {
        try {
            html.setPage(url);
        }
        catch (IOException ex) {
            // ページが開けない場合は特に何もしない。
        }
    }
    
    /**
     * ダイアログを作成する。
     * @param url ヘルプファイルのURL
     * @throws IOException ファイルオープンに失敗
     */
    private void makeDialog(URL url) throws IOException {
        /*-
         * ウィンドウ情報
         * ここらへんはプロパティなどに出しておくと良さそうです。
         *
         */
        setTitle("ヘルプ");
        setSize(400, 500);
        // setIconImages(icon);

        /*-
         * HTML Viewer
         *
         */
        html = new JEditorPane();
        html.setContentType("text/html");
        html.setEditable(false);
        html.addHyperlinkListener(new HyperlinkListener() {
                @Override
                public void hyperlinkUpdate(HyperlinkEvent event) {
                    if (event.getEventType() == EventType.ACTIVATED) {
                        URL newUrl = event.getURL();
                        open( newUrl );
                    }
                }
            });
        
        HTMLDocument doc = (HTMLDocument)html.getDocument();
        doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
	
        html.setPage( url );
	
        scrollPane = new JScrollPane(html);
        getContentPane().add(scrollPane);
    }
}

使い方は見ての通り、

File html = new File(file);
//URL url = new URL("file:" + file.getPath());
URL url = file.toURI().toURL();
HelpDialog dialog = new HelpDialog(null, url);
dialog.setVisible(true);

とやれば、HTMLファイルを表示することができます。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3