@634

簡易テキストエディタ その5 メニュー追加。

Advertisement

メニューの追加

JMenuBarJMenuJMenuItem使ってメニュー作り。あとセパレータ(メニューの横線)はJSeparatorを使う。(リンク先:java.sun.com)

メニュー作ってみよー

いきなりソース。説明はコメント参照。
import javax.swing.*;

public class SwingTest{
    public static void main(String args[]){

        JFrame.setDefaultLookAndFeelDecorated(true);
        try{
            javax.swing.plaf.metal.
            MetalLookAndFeel.setCurrentTheme(
            new javax.swing.plaf.metal.DefaultMetalTheme());

            UIManager.setLookAndFeel
                ("javax.swing.plaf.metal.MetalLookAndFeel");
        }catch(Exception e){
            System.out.println(e);
        }

        MyFrame mf = new MyFrame();
        mf.setTitle("簡易テキストエディタ");
        mf.setSize(400, 300);
        mf.show();
    }
}

class MyFrame extends JFrame{
    JTextPane text;
    JScrollPane spanel;

    //各コンポーネントの宣言
    JMenuBar menuBar;
    JMenu file;
    JMenuItem open, save, quit;

    public MyFrame(){
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        text = new JTextPane();
        spanel = new JScrollPane(text);
        spanel.setVerticalScrollBarPolicy(
                         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        getContentPane().add(spanel);


        //コンポーネント初期化
        menuBar = new JMenuBar();
        file = new JMenu("ファイル");
        open = new JMenuItem("開く");
        save = new JMenuItem("保存");
        quit = new JMenuItem("終了");

        //「ファイル」メニューに各アイテムを追加。
        file.add(open);
        file.add(save);
        file.add(new JSeparator());//セパレータ
        file.add(quit);

        //メニューバーに「ファイル」メニューを追加。
        menuBar.add(file);

        //メニューバーをコンテナに追加。
        setJMenuBar(menuBar);
    }
}
実行イメージ
実行イメージ
次回、つかえるようにしましょ。

Advertisement

ショートカット

634
このカテゴリのトップページに戻る
634labs
   UIコレクションギャラリー

サイト検索

Google

Web サイト内

Y!ログール