Removed some more warnings and cleaned more SWT listeners
[Mograsim.git] / plugins / net.mograsim.plugin.core / src / net / mograsim / plugin / util / DropDownMenu.java
1 package net.mograsim.plugin.util;
2
3 import org.eclipse.swt.SWT;
4 import org.eclipse.swt.graphics.Point;
5 import org.eclipse.swt.graphics.Rectangle;
6 import org.eclipse.swt.widgets.Button;
7 import org.eclipse.swt.widgets.Composite;
8 import org.eclipse.swt.widgets.Menu;
9 import org.eclipse.swt.widgets.MenuItem;
10
11 public class DropDownMenu
12 {
13         private Button button;
14
15         public DropDownMenu(Composite parent, String label, DropDownEntry... entries)
16         {
17                 button = new Button(parent, SWT.PUSH);
18                 button.setText(label);
19                 setupDrowpDownMenu(entries);
20         }
21
22         private void setupDrowpDownMenu(DropDownEntry[] entries)
23         {
24                 Menu menu = new Menu(button);
25                 for (DropDownEntry entry : entries)
26                 {
27                         MenuItem item = new MenuItem(menu, SWT.PUSH);
28                         item.addListener(SWT.Selection, e -> entry.onSelected.run());
29                         item.setText(entry.title);
30                 }
31
32                 button.addListener(SWT.Selection, e ->
33                 {
34                         Rectangle rect = button.getBounds();
35                         Point pt = new Point(rect.x, rect.y + rect.height);
36                         pt = button.getParent().toDisplay(pt);
37                         menu.setLocation(pt.x, pt.y);
38                         menu.setVisible(true);
39                 });
40         }
41
42         public Button getButton()
43         {
44                 return button;
45         }
46
47         public static class DropDownEntry
48         {
49                 public final String title;
50                 public final Runnable onSelected;
51
52                 public DropDownEntry(String title, Runnable onSelected)
53                 {
54                         this.title = title;
55                         this.onSelected = onSelected;
56                 }
57         }
58 }