2018년 9월 15일 토요일

[JavaFx] MenuButton Example


1. MenuButton




Source Code:
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class FxMenuButton extends Application {
    
    //------------------------------------------------------------
    // Menu Button
    //------------------------------------------------------------
    MenuButton menuButton;
    
    public FxMenuButton(String title, String iconFile) {
        menuButton = new MenuButton(title, new ImageView(new Image(getClass().getResourceAsStream(iconFile))));
    }
    
    public FxMenuButton(String title) {
        menuButton = new MenuButton(title);
    }
    
    public FxMenuButton() {
    }
    
    public MenuButton get() {
        return menuButton;
    }
    
    public MenuItem add(String title, String iconFile, Runnable runnable) {
        MenuItem item = new MenuItem( title);
        if( iconFile != null ) {
            item.setGraphic(new ImageView(new Image(getClass().getResourceAsStream(iconFile))));
        }
        item.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                runnable.run();
            }
        });
        menuButton.getItems().add(item);
        return item;
    }

    //------------------------------------------------------------
    // Example
    //------------------------------------------------------------
    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("Menu Button Example");
        stage.getIcons().add(new Image(getClass().getResourceAsStream("/res/Window32.png")));
           
        FxMenuButton menu = new FxMenuButton("Options", "/res/Setting32.png");
        menu.add("Exit", "/res/Exit32.png", new Runnable() {@Override public void run() { System.exit(0); }    });
        menu.add("Save", "/res/Save32.png", new Runnable() {@Override public void run() { }    });
        menu.add("About", "/res/About32.png", new Runnable() {@Override public void run() { } });

        HBox hbox = new HBox(menu.get());
        Scene scene = new Scene(hbox, 320, 240);
        stage.setScene(scene);
        stage.setOnCloseRequest( e -> System.exit(0) );
        stage.show();
    }    
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}


댓글 없음:

댓글 쓰기