タイトル
TOPJavaSwingJTree → This Page

JTree@Swing サンプル03

概要

Java - Swing - JTree のサンプルです。
・ルートノードの表示・非表示
・ルートノード横のアイコンを表示

解説

ルートノードの表示・非表示やルートノード横のアイコンの表示・非表示を切り替えます。

サンプルイメージ

ルートノードを非表示にした状態です。
サンプル画像

ルートノードとルートノード横のアイコンを表示した状態です。
サンプル画像


サンプルソース

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;

/**
 * JTree サンプル03
 * ・ルートノードの表示・非表示
 * ・ルートノード横のアイコンを表示
 * 
 * @author みっちー
 */
public class JTree03 extends JFrame implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	
	/** ツリー */
	JTree tree = null;
	
	/**
	 * 開始メソッド
	 * 
	 * @param args	パラメータ
	 */
	public static void main(String[] args) {
		JTree03 frame = new JTree03();
		
		// 閉じるボタンをクリックされた場合の動作を設定
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// ウインドウのタイトルを設定
		frame.setTitle("JTree サンプル03");
		
		// フレームの X座標、Y座標、幅、高さを設定
		frame.setBounds(100, 200, 750, 150);
		
		// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
		frame.setVisible(true);
	}
	
	/**
	 * コンストラクタ
	 */
	public JTree03() {
		// パネルを作成
		JPanel panelBase = new JPanel();
		
		// 配列を作成
		String[] dataArray = { "water", "cofe", "cola" };
		
		// ツリーを作成
		tree = new JTree(dataArray);
		
		// ボタンを作成
		JButton button1 = new JButton("RootVisible true");
		JButton button2 = new JButton("RootVisible false");
		JButton button3 = new JButton("ShowsRootHandles true");
		JButton button4 = new JButton("ShowsRootHandles false");
		
		// アクションコマンドを設定
		button1.setActionCommand("A");
		button2.setActionCommand("B");
		button3.setActionCommand("C");
		button4.setActionCommand("D");
		
		// アクションリスナー追加
		button1.addActionListener(this);
		button2.addActionListener(this);
		button3.addActionListener(this);
		button4.addActionListener(this);
		
		// ツリー・ボタンを追加
		panelBase.add(tree);
		panelBase.add(button1);
		panelBase.add(button2);
		panelBase.add(button3);
		panelBase.add(button4);
		
		// パネルを追加
		getContentPane().add(panelBase);
	}
	
	/**
	 * アクション
	 */
	public void actionPerformed(ActionEvent e) {
		if ("A".equals(e.getActionCommand())) {
			// ルートノードを表示
			tree.setRootVisible(true);
		} else if ("B".equals(e.getActionCommand())) {
			// ルートノードを非表示
			tree.setRootVisible(false);
		} else if ("C".equals(e.getActionCommand())) {
			// ルートノード横のアイコンを表示
			tree.setShowsRootHandles(true);
		} else if ("D".equals(e.getActionCommand())) {
			// ルートノード横のアイコンを非表示
			tree.setShowsRootHandles(false);
		}
	}
}

サンプルソースのダウンロード

ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)

更新履歴

2016/05/13 新規作成


TOPJavaSwingJTree → This Page