ドキュメント



JavaFX: JavaFX UIコンポヌネントの操䜜

24 メニュヌ

この章では、メニュヌおよびメニュヌ・バヌの䜜成、メニュヌ項目の远加、カテゎリぞのメニュヌのグルヌプ化、サブメニュヌの䜜成、およびコンテキスト・メニュヌの蚭定の方法に぀いお説明したす。

JavaFX APIの次のクラスを䜿甚しお、JavaFXアプリケヌション内でメニュヌをビルドできたす。

  • MenuBar

  • MenuItem

    • Menu

    • CheckMenuItem

    • RadioMenuItem

    • Menu

    • CustomMenuItem

      • SeparatorMenuItem

  • ContextMenu

図24-1に、䞀般的なメニュヌ・バヌがあるアプリケヌションのスクリヌン・キャプチャを瀺したす。

図24-1 メニュヌ・バヌず3぀のメニュヌ・カテゎリがあるアプリケヌション

図24-1の説明が続きたす
「図24-1 メニュヌ・バヌず3぀のメニュヌ・カテゎリがあるアプリケヌション」の説明

JavaFXアプリケヌションでのメニュヌのビルド

メニュヌは、ナヌザヌのリク゚ストに応じお衚瀺できるアクション可胜な項目のリストです。 メニュヌが衚瀺されおいる堎合、䞀床に1぀のメニュヌ項目を遞択できたす。 項目をクリックした埌、メニュヌは非衚瀺モヌドに戻りたす。 メニュヌを䜿甚するこずにより、垞時衚瀺する必芁がない機胜をメニュヌ内に配眮しお、アプリケヌション・ナヌザヌ・むンタフェヌス(UI)内のスペヌスを節玄できたす。

通垞、メニュヌ・バヌ内のメニュヌはカテゎリにグルヌプ化されおいたす。 コヌディング・パタヌンずしおは、メニュヌ・バヌを宣蚀し、カテゎリ・メニュヌを定矩し、カテゎリ・メニュヌにメニュヌ項目を移入したす。 JavaFXアプリケヌション内でメニュヌをビルドする堎合、次のメニュヌ項目クラスを䜿甚したす。

  • MenuItem - 1぀のアクション可胜なオプションを䜜成したす

  • Menu - サブメニュヌを䜜成したす

  • RadioButtonItem - 盞互に排他的な遞択肢を䜜成したす

  • CheckMenuItem - 遞択状態ず遞択解陀状態を切り替えるこずができるオプションを䜜成したす

1぀のカテゎリ内のメニュヌ項目を区切るには、SeparatorMenuItemクラスを䜿甚したす。

通垞、メニュヌ・バヌでカテゎリによっお構成されたメニュヌはりィンドりの䞊郚に配眮され、シヌンの残りの郚分は重芁なUI芁玠のために残されたす。 なんらかの理由によっおUIの可芖郚分をメニュヌ・バヌに割り圓おるこずができない堎合は、ナヌザヌがマりス・クリックで開くコンテキスト・メニュヌを䜿甚できたす。

メニュヌ・バヌの䜜成

メニュヌ・バヌはナヌザヌ・むンタフェヌス内の任意の堎所に配眮できたすが、通垞は、りィンドりの䞊郚に配眮され、1぀以䞊のメニュヌが含たれたす。 メニュヌ・バヌはアプリケヌション・りィンドりの幅に合せお自動的にサむズが倉曎されたす。 デフォルトでは、メニュヌ・バヌに远加される各メニュヌは、テキスト倀を持぀ボタンによっお衚されたす。

怍物に関する参照情報(名前、分類孊䞊の名前、画像および簡単な説明など)をレンダリングするアプリケヌションに぀いお考えおみたす。 「File」、「Edit」および「View」ずいう3぀のメニュヌ・カテゎリを䜜成し、これらにメニュヌ項目を移入できたす。 䟋24-1に、メニュヌ・バヌが远加されたこのようなアプリケヌションの゜ヌス・コヌドを瀺したす。

䟋24-1 メニュヌのサンプル・アプリケヌション

import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.effect.SepiaTone;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class MenuSample extends Application {
 
    final PageData[] pages = new PageData[] {
        new PageData("Apple",
            "The apple is the pomaceous fruit of the apple tree, species Malus "
            + "domestica in the rose family (Rosaceae). It is one of the most "
            + "widely cultivated tree fruits, and the most widely known of "
            + "the many members of genus Malus that are used by humans. "
            + "The tree originated in Western Asia, where its wild ancestor, "
            + "the Alma, is still found today.",
            "Malus domestica"),
        new PageData("Hawthorn",
            "The hawthorn is a large genus of shrubs and trees in the rose "
            + "family, Rosaceae, native to temperate regions of the Northern "
            + "Hemisphere in Europe, Asia and North America. "
            + "The name hawthorn was "
            + "originally applied to the species native to northern Europe, "
            + "especially the Common Hawthorn C. monogyna, and the unmodified "
            + "name is often so used in Britain and Ireland.",
            "Crataegus monogyna"),
        new PageData("Ivy",
            "The ivy is a flowering plant in the grape family (Vitaceae) native to"
            + " eastern Asia in Japan, Korea, and northern and eastern China. "
            + "It is a deciduous woody vine growing to 30 m tall or more given "
            + "suitable support,  attaching itself by means of numerous small "
            + "branched tendrils tipped with sticky disks.",
            "Parthenocissus tricuspidata"),
        new PageData("Quince",
            "The quince is the sole member of the genus Cydonia and is native to "
            + "warm-temperate southwest Asia in the Caucasus region. The "
            + "immature fruit is green with dense grey-white pubescence, most "
            + "of which rubs off before maturity in late autumn when the fruit "
            + "changes color to yellow with hard, strongly perfumed flesh.",
            "Cydonia oblonga")
    };
 
    final String[] viewOptions = new String[] {
        "Title", 
        "Binomial name", 
        "Picture", 
        "Description"
    };
 
    final Entry<String, Effect>[] effects = new Entry[] {
        new SimpleEntry<>("Sepia Tone", new SepiaTone()),
        new SimpleEntry<>("Glow", new Glow()),
        new SimpleEntry<>("Shadow", new DropShadow())
    };
 
    final ImageView pic = new ImageView();
    final Label name = new Label();
    final Label binName = new Label();
    final Label description = new Label();
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) {
        stage.setTitle("Menu Sample");
        Scene scene = new Scene(new VBox(), 400, 350);
         
        MenuBar menuBar = new MenuBar();
 
        // --- Menu File
        Menu menuFile = new Menu("File");
 
        // --- Menu Edit
        Menu menuEdit = new Menu("Edit");
 
        // --- Menu View
        Menu menuView = new Menu("View");
 
        menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
 
 
        ((VBox) scene.getRoot()).getChildren().addAll(menuBar);
 
        stage.setScene(scene);
        stage.show();
    }
 
 
    private class PageData {
        public String name;
        public String description;
        public String binNames;
        public Image image;
        public PageData(String name, String description, String binNames) {
            this.name = name;
            this.description = description;
            this.binNames = binNames;
            image = new Image(getClass().getResourceAsStream(name + ".jpg"));
        }
    }
}

他のUIコントロヌルずは異なり、MenuクラスおよびMenuItemクラスの他の拡匵機胜によっおNodeクラスは拡匵されたせん。 これらは、アプリケヌション・シヌンに盎接远加するこずはできず、getMenusメ゜ッドを介しおメニュヌ・バヌに远加されるたでは衚瀺されたせん。

図24-2 アプリケヌションに远加されたメニュヌ・バヌ

図24-2の説明が続きたす
「図24-2 アプリケヌションに远加されたメニュヌ・バヌ」の説明

メニュヌ内を移動するには、キヌボヌドの矢印キヌを䜿甚したす。 ただし、メニュヌを遞択しおも、メニュヌの動䜜がただ定矩されおいないため、アクションは実行されたせん。

メニュヌ項目の远加

次の項目を远加するこずにより、「File」メニュヌの機胜を蚭定したす。

  • Shuffle - 怍物に関する参照情報をロヌドしたす

  • Clear - 参照情報を削陀し、シヌンをクリアしたす

  • Separator - メニュヌ項目をデタッチしたす

  • Exit - アプリケヌションを終了したす

䟋24-2の倪字の行では、MenuItemクラスを䜿甚しお「Shuffle」メニュヌを䜜成し、アプリケヌション・シヌンにグラフィカル・コンポヌネントを远加しおいたす。 MenuItemクラスを䜿甚するず、テキストずグラフィックを䜿甚しおアクション可胜な項目を䜜成できたす。 ナヌザヌがクリックしたずきに実行されるアクションは、Buttonクラスず同じように、setOnActionメ゜ッドによっお定矩されたす。

䟋24-2 グラフィックを䜿甚した「Shuffle」メニュヌ項目の远加

import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.effect.SepiaTone;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
 
public class MenuSample extends Application {
 
    final PageData[] pages = new PageData[] {
        new PageData("Apple",
            "The apple is the pomaceous fruit of the apple tree, species Malus "
            +"domestica in the rose family (Rosaceae). It is one of the most "
            +"widely cultivated tree fruits, and the most widely known of "
            +"the many members of genus Malus that are used by humans. "
            +"The tree originated in Western Asia, where its wild ancestor, "
            +"the Alma, is still found today.",
            "Malus domestica"),
        new PageData("Hawthorn",
            "The hawthorn is a large genus of shrubs and trees in the rose "
            + "family, Rosaceae, native to temperate regions of the Northern "
            + "Hemisphere in Europe, Asia and North America. "
            + "The name hawthorn was "
            + "originally applied to the species native to northern Europe, "
            + "especially the Common Hawthorn C. monogyna, and the unmodified "
            + "name is often so used in Britain and Ireland.",
            "Crataegus monogyna"),
        new PageData("Ivy",
            "The ivy is a flowering plant in the grape family (Vitaceae) native"
            +" to eastern Asia in Japan, Korea, and northern and eastern China."
            +" It is a deciduous woody vine growing to 30 m tall or more given "
            +"suitable support,  attaching itself by means of numerous small "
            +"branched tendrils tipped with sticky disks.",
            "Parthenocissus tricuspidata"),
        new PageData("Quince",
            "The quince is the sole member of the genus Cydonia and is native"
            +" to warm-temperate southwest Asia in the Caucasus region. The "
            +"immature fruit is green with dense grey-white pubescence, most "
            +"of which rubs off before maturity in late autumn when the fruit "
            +"changes color to yellow with hard, strongly perfumed flesh.",
            "Cydonia oblonga")
    };
 
    final String[] viewOptions = new String[] {
        "Title", 
        "Binomial name", 
        "Picture", 
        "Description"
    };
 
    final Entry<String, Effect>[] effects = new Entry[] {
        new SimpleEntry<>("Sepia Tone", new SepiaTone()),
        new SimpleEntry<>("Glow", new Glow()),
        new SimpleEntry<>("Shadow", new DropShadow())
    };
 
    final ImageView pic = new ImageView();
    final Label name = new Label();
    final Label binName = new Label();
    final Label description = new Label();
    private int currentIndex = -1;
 
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage stage) {
        stage.setTitle("Menu Sample");
        Scene scene = new Scene(new VBox(), 400, 350);
        scene.setFill(Color.OLDLACE);
 
        name.setFont(new Font("Verdana Bold", 22));
        binName.setFont(new Font("Arial Italic", 10));
        pic.setFitHeight(150);
        pic.setPreserveRatio(true);
        description.setWrapText(true);
        description.setTextAlignment(TextAlignment.JUSTIFY);
 
        shuffle();
 
        MenuBar menuBar = new MenuBar();
 
        final VBox vbox = new VBox();
        vbox.setAlignment(Pos.CENTER);
        vbox.setSpacing(10);
        vbox.setPadding(new Insets(0, 10, 0, 10));
        vbox.getChildren().addAll(name, binName, pic, description);
 
        // --- Menu File
        Menu menuFile = new Menu("File");
        MenuItem add = new MenuItem("Shuffle",
            new ImageView(new Image("menusample/new.png")));
        add.setOnAction((ActionEvent t) -> {
            shuffle();
            vbox.setVisible(true);
        });        
 
        menuFile.getItems().addAll(add);
 
        // --- Menu Edit
        Menu menuEdit = new Menu("Edit");
        
        // --- Menu View
        Menu menuView = new Menu("View");
        
        menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
        ((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);
        stage.setScene(scene);
        stage.show();
    }
 
    private void shuffle() {
        int i = currentIndex;
        while (i == currentIndex) {
            i = (int) (Math.random() * pages.length);
        }
        pic.setImage(pages[i].image);
        name.setText(pages[i].name);
        binName.setText("(" + pages[i].binNames + ")");
        description.setText(pages[i].description);
        currentIndex = i;
    }
 
    
    private class PageData {
        public String name;
        public String description;
        public String binNames;
        public Image image;
        public PageData(String name, String description, String binNames) {
            this.name = name;
            this.description = description;
            this.binNames = binNames;
            image = new Image(getClass().getResourceAsStream(name + ".jpg"));
        }
    }
}

ナヌザヌが「Shuffle」メニュヌ項目を遞択するず、setOnAction内でコヌルされたshuffleメ゜ッドにより、察応する配列内の芁玠の玢匕が蚈算され、怍物のタむトル、分類孊䞊の名前、画像および説明が指定されたす。

「Clear」メニュヌ項目は、アプリケヌション・シヌンを削陀するために䜿甚されたす。 これを実装するには、䟋24-3に瀺すように、GUI芁玠があるVBoxを非衚瀺にしたす。

䟋24-3 アクセラレヌタを䜿甚した「Clear」メニュヌ項目の䜜成

MenuItem clear = new MenuItem("Clear");
clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
clear.setOnAction((ActionEvent t) -> {
    vbox.setVisible(false);
});

MenuItemクラスを実装するこずにより、開発者は、メニュヌ・アクセラレヌタや、メニュヌ項目ず同じアクションを実行するキヌの組合せを蚭定できるようになりたす。 「Clear」メニュヌを䜿甚するず、ナヌザヌは、「File」メニュヌ・カテゎリからアクションを遞択したり、コントロヌル・キヌず[X]キヌを同時に抌すこずができるようになりたす。

「Exit」メニュヌを䜿甚するず、アプリケヌション・りィンドりが閉じたす。 䟋24-4に瀺すように、このメニュヌ項目のアクションずしおSystem.exit(0)を蚭定したす。

䟋24-4 「Exit」メニュヌ項目の䜜成

MenuItem exit = new MenuItem("Exit");
exit.setOnAction((ActionEvent t) -> {
    System.exit(0);
});

䟋24-5に瀺すgetItemsメ゜ッドを䜿甚しお、新しく䜜成したメニュヌ項目を「File」メニュヌに远加したす。 セパレヌタ・メニュヌ項目を䜜成し、getItemsメ゜ッド内に远加するこずにより、「Exit」メニュヌ項目を芖芚的にデタッチできたす。

䟋24-5 メニュヌ項目の远加

menuFile.getItems().addAll(add, clear, new SeparatorMenuItem(), exit);

䟋24-2、䟋24-3、䟋24-4および䟋24-5を「Menu Sample」アプリケヌションに远加しおから、コンパむルしお実行したす。 「Shuffle」メニュヌ項目を遞択し、様々な怍物に関する参照情報をロヌドしたす。 次に、シヌンをクリアし(Clear)、アプリケヌションを閉じたす(Exit)。 図24-3に、「Clear」メニュヌ項目の遞択を瀺したす。

図24-3 3぀のメニュヌ項目がある「File」メニュヌ

図24-3の説明が続きたす
「図24-3 3぀のメニュヌ項目がある「File」メニュヌ」の説明

「View」メニュヌを䜿甚するず、参照情報の芁玠の衚瀺ず非衚瀺を切り替えるこずができたす。 createMenuItemメ゜ッドを実装し、startメ゜ッド内でコヌルし、4぀のCheckMenuItemオブゞェクトを䜜成したす。 次に、新しく䜜成したチェック・マヌク項目を「View」メニュヌに远加し、怍物のタむトル、分類孊䞊の名前、画像および説明の可芖性を切り替えたす。 䟋24-6に、これらのタスクを実装するコヌド・フラグメントを瀺したす。

䟋24-6 CheckMenuItemクラスの適甚による切替えオプションの䜜成

// --- Creating four check menu items within the start method
CheckMenuItem titleView = createMenuItem ("Title", name);                                                       
CheckMenuItem binNameView = createMenuItem ("Binomial name", binName);        
CheckMenuItem picView = createMenuItem ("Picture", pic);        
CheckMenuItem descriptionView = createMenuItem ("Description", description);     
menuView.getItems().addAll(titleView, binNameView, picView, descriptionView);

...

// The createMenuItem method
private static CheckMenuItem createMenuItem (String title, final Node node){
    CheckMenuItem cmi = new CheckMenuItem(title);
    cmi.setSelected(true);
    cmi.selectedProperty().addListener(
        (ObservableValue<? extends Boolean> ov, Boolean old_val, 
        Boolean new_val) -> {
            node.setVisible(new_val);
    });              
    return cmi;
}

CheckMenuItemクラスは、MenuItemの拡匵機です。 これは、遞択枈状態ず遞択解陀枈状態を切り替えるこずができたす。 遞択枈の堎合、チェック・マヌク項目によっおチェック・マヌクが衚瀺されたす。

䟋24-6では、4぀のCheckMenuItemオブゞェクトを䜜成し、それらのselectedPropertyプロパティの倉曎を凊理しおいたす。 たずえば、ナヌザヌがpicView項目の遞択を解陀するず、setVisibleメ゜ッドはfalse倀を受け取り、怍物の画像は非衚瀺になりたす。 このコヌドをアプリケヌションのフラグメントに远加し、アプリケヌションをコンパむルしお実行するず、メニュヌ項目の遞択ず遞択解陀を詊すこずができたす。 図24-4に、怍物のタむトルず画像は衚瀺されおいるが、分類孊䞊の名前ず説明は衚瀺されおいない状態のアプリケヌションを瀺したす。

図24-4 チェック・メニュヌ項目の䜿甚

図24-4の説明が続きたす
「図24-4 チェック・メニュヌ項目の䜿甚」の説明

サブメニュヌの䜜成

「Edit」メニュヌの堎合、「Picture Effect」および「No Effects」の2぀のメニュヌ項目を定矩したす。 「Picture Effect」メニュヌ項目は、䜿甚可胜な3぀の芖芚効果の1぀を蚭定するための項目が3぀あるサブメニュヌずしお蚭蚈されたす。 「No Effects」メニュヌ項目により、遞択した効果を削陀し、むメヌゞの初期状態をリストアしたす。

RadioMenuItemクラスを䜿甚しお、サブメニュヌの項目を䜜成したす。 ラゞオ・メニュヌ・ボタンをトグル・グルヌプに远加し、遞択を盞互に排他的にしたす。 䟋24-7では、これらのタスクを実装しおいたす。

䟋24-7 ラゞオ・メニュヌ項目を䜿甚したサブメニュヌの䜜成

//Picture Effect menu
Menu menuEffect = new Menu("Picture Effect");
final ToggleGroup groupEffect = new ToggleGroup();
for (Entry<String, Effect> effect : effects) {
    RadioMenuItem itemEffect = new RadioMenuItem(effect.getKey());
    itemEffect.setUserData(effect.getValue());
    itemEffect.setToggleGroup(groupEffect);
    menuEffect.getItems().add(itemEffect);
}
//No Effects menu
final MenuItem noEffects = new MenuItem("No Effects");

noEffects.setOnAction((ActionEvent t) -> {
    pic.setEffect(null);
    groupEffect.getSelectedToggle().setSelected(false);
});

//Processing menu item selection
groupEffect.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
    public void changed(ObservableValue<? extends Toggle> ov,
        Toggle old_toggle, Toggle new_toggle) {
            if (groupEffect.getSelectedToggle() != null) {
                Effect effect = 
                    (Effect) groupEffect.getSelectedToggle().getUserData();
                pic.setEffect(effect);
            }
        }
 });
groupEffect.selectedToggleProperty().addListener(
    (ObservableValue<? extends Toggle> ov, Toggle old_toggle, 
    Toggle new_toggle) -> {
        if (groupEffect.getSelectedToggle() != null) {
             Effect effect = 
                 (Effect) groupEffect.getSelectedToggle().getUserData();
             pic.setEffect(effect);
        }
});

//Adding items to the Edit menu
menuEdit.getItems().addAll(menuEffect, noEffects);

setUserDataメ゜ッドにより、特定のラゞオ・メニュヌ項目の芖芚効果を定矩しおいたす。 トグル・グルヌプ内の項目の1぀を遞択するず、察応する効果が画像に適甚されたす。 「No Effects」メニュヌ項目を遞択するず、setEffectにより、null倀が指定され、画像に効果が適甚されたせん。

図24-5は、ナヌザヌが「Shadow」メニュヌ項目を遞択する瞬間を捉えおいたす。

図24-5 3぀のラゞオ・メニュヌ項目があるサブメニュヌ

図24-5の説明が続きたす
「図24-5 3぀のラゞオ・メニュヌ項目があるサブメニュヌ」の説明

DropShadow効果を画像に適甚するず、図24-6に瀺すようになりたす。

図24-6 DropShadow効果が適甚されたQuinceの画像

図24-6の説明が続きたす
「図24-6 DropShadow効果が適甚されたQuinceの画像」の説明

MenuItemクラスのsetDisableメ゜ッドを䜿甚するず、「Picture Effect」サブメニュヌで効果が遞択されおいないずきに「No Effects」メニュヌを無効にできたす。 䟋24-8に瀺すように、䟋24-7を倉曎したす。

䟋24-8 メニュヌ項目の無効化

Menu menuEffect = new Menu("Picture Effect");
final ToggleGroup groupEffect = new ToggleGroup();
for (Entry<String, Effect> effect : effects) {
     RadioMenuItem itemEffect = new RadioMenuItem(effect.getKey());
     itemEffect.setUserData(effect.getValue());
     itemEffect.setToggleGroup(groupEffect);
     menuEffect.getItems().add(itemEffect);
}
final MenuItem noEffects = new MenuItem("No Effects");
noEffects.setDisable(true);
noEffects.setOnAction((ActionEvent t) -> {
    pic.setEffect(null);
    groupEffect.getSelectedToggle().setSelected(false);
    noEffects.setDisable(true);
});

groupEffect.selectedToggleProperty().addListener(
    (ObservableValue<? extends Toggle> ov, Toggle old_toggle, 
    Toggle new_toggle) -> {
        if (groupEffect.getSelectedToggle() != null) {
            Effect effect = 
                (Effect) groupEffect.getSelectedToggle().getUserData();
            pic.setEffect(effect);
            noEffects.setDisable(false);
        } else {
                noEffects.setDisable(true);
            }
});
        
menuEdit.getItems().addAll(menuEffect, noEffects);

RadioMenuItemオプションが遞択されおいない堎合、図24-7に瀺すように、「No Effect」メニュヌ項目が無効になりたす。 ナヌザヌが芖芚効果の1぀を遞択するず、「No Effects」メニュヌ項目が有効になりたす。

図24-7 無効になった「Effect」メニュヌ項目

図24-7の説明が続きたす
「図24-7 無効になった「Effect」メニュヌ項目」の説明

コンテキスト・メニュヌの远加

必芁な機胜にナヌザヌ・むンタフェヌスのスペヌスを割り圓おるこずができない堎合、コンテキスト・メニュヌを䜿甚できたす。 コンテキスト・メニュヌは、マりスのクリックに応じお衚瀺されるポップアップ・りィンドりです。 1぀のコンテキスト・メニュヌには、1぀以䞊のメニュヌ項目を含めるこずができたす。

「Menu Sample」アプリケヌションで、怍物の画像にコンテキスト・メニュヌを蚭定し、ナヌザヌが画像をコピヌできるようにしたす。

ContextMenuクラスを䜿甚しお、䟋24-9に瀺すように、コンテキスト・メニュヌを定矩したす。

䟋24-9 コンテキスト・メニュヌの定矩

final ContextMenu cm = new ContextMenu();
MenuItem cmItem1 = new MenuItem("Copy Image");
cmItem1.setOnAction((ActionEvent e) -> {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    ClipboardContent content = new ClipboardContent();
    content.putImage(pic.getImage());
    clipboard.setContent(content);
});

cm.getItems().add(cmItem1);
pic.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
    if (e.getButton() == MouseButton.SECONDARY)
       cm.show(pic, e.getScreenX(), e.getScreenY());
});

ナヌザヌがImageViewオブゞェクトを右クリックするず、コンテキスト・メニュヌに察しおshowメ゜ッドがコヌルされ、その衚瀺が可胜になりたす。

コンテキスト・メニュヌの「Copy Image」項目に定矩されおいるsetOnActionメ゜ッドにより、Clipboardオブゞェクトが䜜成され、そのコンテンツずしおむメヌゞが远加されたす。 図24-8は、ナヌザヌが「Copy Image」コンテキスト・メニュヌ項目を遞択する瞬間を捉えおいたす。

図24-8 コンテキスト・メニュヌの䜿甚

図24-8の説明が続きたす
「図24-8 コンテキスト・メニュヌの䜿甚」の説明

むメヌゞをコピヌしおグラフィカル・゚ディタに貌り付けるこずができたす。

さらに拡匵する堎合は、コンテキスト・メニュヌにメニュヌ項目を远加し、別のアクションを指定できたす。 たた、CustomMenuItemクラスを䜿甚しおカスタム・メニュヌを䜜成するこずもできたす。 このクラスを䜿甚するず、メニュヌ内に任意のノヌドを埋め蟌み、たずえば、ボタンやスラむダをメニュヌ項目ずしお指定できたす。

関連APIドキュメント

りィンドりを閉じる

目次

JavaFX: JavaFX UIコンポヌネントの操䜜

展開 | 瞮小