TOP →
Java →
Swing →
JMenuBar,JMenu,JMenuItem → This Page
JMenuBar@Swing サンプル02
概要
Java -
Swing -
JMenuBar のサンプルです。
・メニューを追加
・メニューを削除
・非表示化
・表示化
解説
メニューバーに動的にメニューを追加・削除したり、
メニューバーの表示・非表示を切り替えます。
サンプルイメージ
サンプルソース
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
/**
* JMenuBar サンプル02
* ・メニューを追加
* ・メニューを削除
* ・非表示化
* ・表示化
*
* @author みっちー
*/
public class JMenuBar02 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
/** メニューバー */
JMenuBar menubar = null;
/** メニュー */
JMenu menu1 = null;
JMenu menu2 = null;
JMenu menu3 = null;
/** ボタン */
JButton button1 = null;
JButton button2 = null;
JButton button3 = null;
JButton button4 = null;
/**
* 開始メソッド
*
* @param args パラメータ
*/
public static void main(String[] args) {
JMenuBar02 frame = new JMenuBar02();
// 閉じるボタンをクリックされた場合の動作を設定
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウインドウのタイトルを設定
frame.setTitle("JMenuBar サンプル02");
// フレームの X座標、Y座標、幅、高さを設定
frame.setBounds(100, 200, 480, 120);
// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
frame.setVisible(true);
}
/**
* コンストラクタ
*/
public JMenuBar02() {
// パネルを作成
JPanel panelBase = new JPanel();
// メニューバーを作成
menubar = new JMenuBar();
// メニューを作成
menu1 = new JMenu("File");
menu2 = new JMenu("Edit");
menu3 = new JMenu("Source");
// メニューバーにメニューを追加
menubar.add(menu1);
menubar.add(menu2);
// メニューアイテムを作成
JMenuItem menu1item1 = new JMenuItem("New");
// メニューにアイテムを追加
menu1.add(menu1item1);
// メニューバーを追加
setJMenuBar(menubar);
// ボタンを作成
button1 = new JButton("Add Menu");
button2 = new JButton("Remove Menu");
button3 = new JButton("Hide MenuBar");
button4 = new JButton("Show MenuBar");
// アクションリスナー追加
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
// ボタンを追加
panelBase.add(button1);
panelBase.add(button2);
panelBase.add(button3);
panelBase.add(button4);
// パネルを追加
getContentPane().add(panelBase);
}
/**
* アクション
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(button1)) {
// メニューを追加
menubar.add(menu3);
menubar.repaint();
menubar.revalidate();
} else if (e.getSource().equals(button2)) {
// メニューを削除
menubar.remove(menu2);
menubar.repaint();
} else if (e.getSource().equals(button3)) {
// 非表示化
menubar.setVisible(false);
} else if (e.getSource().equals(button4)) {
// 表示化
menubar.setVisible(true);
}
}
}
サンプルソースのダウンロード
ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)
更新履歴
2016/05/13 新規作成
TOP →
Java →
Swing →
JMenuBar,JMenu,JMenuItem → This Page