解答例 - 実習課題3 - 13.ツリー
(実習課題3)
実習課題1のプログラムを改良しなさい。
- ノード(またはリーフ)を選択したときに、選択されているノード(またはリーフ)を全てダイアログに表示する事。
解答例
/** * JTreeSelectionFrame.java * TECHSCORE Javaユーザインタフェース13章 実習課題3 * * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.ui.chapter13.exercise3; import java.awt.Dimension; import java.util.Hashtable; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; public class JTreeSelectionFrame extends JFrame implements TreeSelectionListener { private JTree tree; public JTreeSelectionFrame() { super("JTreeSelectionFrame"); setDefaultCloseOperation(EXIT_ON_CLOSE); // JTreeの生成 String[] lowerCases = { "a", "b", "c" }; String[] upperCases = { "A", "B", "C" }; Hashtable alphabets = new Hashtable(); alphabets.put("小文字", lowerCases); alphabets.put("大文字", upperCases); String[] kanas = { "い", "ろ", "は" }; String[] kanjis = { "山", "海", "空" }; Hashtable japanese = new Hashtable(); japanese.put("ひらがな", kanas); japanese.put("漢字", kanjis); Hashtable root = new Hashtable(); root.put("英字", alphabets); root.put("和字", japanese); tree = new JTree(root); tree.addTreeSelectionListener(this); tree.setPreferredSize(new Dimension(250, 400)); getContentPane().add(tree); pack(); } public void valueChanged(TreeSelectionEvent event) { TreePath[] paths = tree.getSelectionPaths(); String[] names = new String[paths.length]; for (int i = 0; i < paths.length; i++) { names[i] = paths[i].getLastPathComponent().toString(); } JOptionPane.showMessageDialog( this, names, "SELECTION", JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args) { new JTreeSelectionFrame().setVisible(true); } }