How to create a mouse rightclick menu for a jface treeviewer - java

I have created a TreeViewer using JFace, but now I have to add a right click listener to the nodes. When the right click is done it has to show a menu like:
Do something
Do Nothing
Delete
I am trying to do this as follows, but it is throwing a null pointer exception.
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
#Override
public void menuAboutToShow(IMenuManager menuManager) {
IContributionManager menu = null;
MenuItem[] items = (MenuItem[]) menu.getItems();
for (int i = 0; i < items.length; i++)
items[i].dispose();
MenuItem itemCollectionFolder = new MenuItem((Menu) menu, SWT.NONE);
itemCollectionFolder.setText("Add Something" );
MenuItem itemNewTestCase = new MenuItem((Menu) menu, SWT.NONE);
itemNewTestCase.setText("Do Nothing" );
}
});
Control tree = treeViewer.getControl();
Menu menu = menuMgr.createContextMenu(tree);
tree.setMenu(menu);

Try this, don't forget to call:
createContextMenu(viewer);
/**
* Creates the context menu
*
* #param viewer
*/
protected void createContextMenu(Viewer viewer) {
MenuManager contextMenu = new MenuManager("#ViewerMenu"); //$NON-NLS-1$
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(new IMenuListener() {
#Override
public void menuAboutToShow(IMenuManager mgr) {
fillContextMenu(mgr);
}
});
Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
}
/**
* Fill dynamic context menu
*
* #param contextMenu
*/
protected void fillContextMenu(IMenuManager contextMenu) {
contextMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
contextMenu.add(new Action("Do Something") {
#Override
public void run() {
// implement this
}
});
contextMenu.add(new Action("Do Nothing") {
#Override
public void run() {
// don't do anything here
}
});
contextMenu.add(new Action("Delete") {
#Override
public void run() {
// implement this
}
});
}
To get the selected element of the treeviewer, do this:
IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
selection.getFirstElement();
selection.toList(); // or if you handle multi selection

Related

Java SWT: Accelerator shortcut not working on PopUp context menus

I'm adding a PopUp menu to one of my widgets, a Table. It is not working! I only achieved to make work accelerator shortcuts if they are on top menu bar items, and not in popup context menu items. Why?
This is my code, but the table is inside a Composite which is inside another composite:
membersTable.setMenu(createMembersPopUpMenu(this));
private Menu createMembersPopUpMenu(Composite parent) {
Menu popUpMenu = new Menu(parent);
//Copy
copyMemberItem = new MenuItem(popUpMenu, SWT.PUSH);
copyMemberItem.setText("Copiar Miembro");
copyMemberItem.setAccelerator(SWT.MOD1 + 'C');
copyMemberItem.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
copyMember();
}
});
//Paste
pasteMemberItem = new MenuItem(popUpMenu, SWT.PUSH);
pasteMemberItem.setText("Pegar Miembro");
pasteMemberItem.setAccelerator(SWT.MOD1 + 'V');
pasteMemberItem.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
pasteMember();
}
});
return popUpMenu;
}

Show/Hide Application from/to System Tray

I need some guidance in how to get the application to show up from the System Tray when I click on it.
I have managed to minimize the app on closure but I can't make it to show up.
If I'm builduing a new shell with same Contents would help?(I am building a SWT application)
This is how I am initializing my Shell: (I have modified it so I don't use AWT with SWT)
protected Shell shlSmartHouseSystem;
public void open() {
Display display = Display.getDefault();
createContents();
shlSmartHouseSystem.open();
shlSmartHouseSystem.layout();
while (!shlSmartHouseSystem.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
And this is my function where I am minimizing in Tray:
public void minimizeToTrayOnClose() {
final Display display = shlSmartHouseSystem.getDisplay();
Image image = new Image(display,"D:\\VIA_University_(Embedded_Systems)\\AJP_Workspace\\HouseSystem_Server\\icon-smart-house.png");
Tray tray = display.getSystemTray();
if (tray != null) {
TrayItem trayItm = new TrayItem(tray,SWT.NONE);
trayItm.setImage(image);
final Menu menu = new Menu(shlSmartHouseSystem, SWT.POP_UP);
MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Show");
menuItem.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
System.out.println("Opened");
}
});
menuItem = new MenuItem(menu, SWT.PUSH);
menuItem.setText("Exit");
menuItem.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
System.exit(0);
}
});
trayItm.addListener (SWT.MenuDetect, new Listener () {
public void handleEvent (Event event) {
menu.setVisible (true);
}
});
}
}

JavaFx Spreadsheet Cell Right Click Open Dialog

I am new to SpreadSheet functionality of ControlsFx Api. I would like to open Dialog on right click of Spreadsheetcell of SpreadsheetView in Javafx. Any help is greatly appreciated.
this is code where you can off the standard ContextMenu and implements own handler with Dialog, in this example TextInputDialog:
SpreadsheetView spreadsheetView = new SpreadsheetView();
//off the standard ContextMenu
spreadsheetView.setContextMenu(null);
//set own handler for right click with Dialog
spreadsheetView.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
#Override public void handle(ContextMenuEvent event) {
CellView cellView = (CellView) event.getTarget();
TextInputDialog dialog = new TextInputDialog(cellView.getText());
Optional<String> result = dialog.showAndWait();
if (result.isPresent()){
System.out.println(cellView.getText());
}
}
});
I don't know very good this library, but it works good.
Example how it works:
My program:
public class MainController extends Application {
public static void main(String[] args) {
launch(args);
}
#Override public void start(Stage primaryStage) throws Exception {
SpreadsheetView spreadsheetView = new SpreadsheetView();
//off the standard ContextMenu
spreadsheetView.setContextMenu(null);
//set own handler for right click with Dialog
spreadsheetView.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
#Override public void handle(ContextMenuEvent event) {
CellView cellView = (CellView) event.getTarget();
TextInputDialog dialog = new TextInputDialog(cellView.getText());
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
System.out.println(cellView.getText());
}
}
});
HBox hBox = new HBox();
hBox.getChildren().add(spreadsheetView);
Scene scene = new Scene(hBox);
primaryStage.setScene(scene);
primaryStage.show();
}
}
It is using mouse handler on the table view which checks when mouse is clicked and on clicking it fires a new dialogue in fx and then accepts the input and updates the fx table view.
table.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 1) {
Call dialogue method of java fx
}
}
});
Or if you want right click you can create cell
Eg
FirstNameCol.setCellFactory(new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
#Override
public TableCell<Person, String> call(TableColumn<Person, String> col) {
final TableCell<Person, String> cell = new TableCell<>();
cell.textProperty().bind(cell.itemProperty()); // in general might need to subclass TableCell and override updateItem(...) here
cell.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton == MouseButton.SECONDARY) {
// handle right click on cell...
// access cell data with cell.getItem();
// access row data with (Person)cell.getTableRow().getItem();
}
}
});
return cell ;
}
});

How to know the row of a dynamic created button of a tableview on javafx

I'm currently working on javafx and I have a serious problem. I can't find a way to get the index of the row of a button that I created dynamically on a table view.
If someone could help me out, that would be very helpful.
this.clmColumn.setCellFactory((TableColumn<?, ?> column) -> {
return new TableCell<?, ?>() {
#Override
protected void updateItem(? item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
final HBox hbox = new HBox(5);
final VBox vbox = new VBox(5);
Label label = new Label(item.toString());
final Button btnMais = new Button("+");
btnMais.setMinSize(25, 25);
final TableCell<?, ?> c = this;
btnMais.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// At this point i want to select the current ROW of the button that i pressed on the tableview.
}
});
final Button btnMenos = new Button("-");
btnMenos.setMinSize(25, 25);
btnMenos.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (getItem() > 1) {
// At this point i want to select the current ROW of the button that i pressed on the tableview.
}
}
});
final Button btnRemover = new Button("Remover");
btnRemover.setFont(new Font(8));
btnRemover.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// At this point i want to select the current ROW of the button that i pressed on the tableview.
}
});
vbox.getChildren().add(hbox);
vbox.getChildren().add(btnRemover);
hbox.getChildren().add(btnMais);
hbox.getChildren().add(label);
hbox.getChildren().add(btnMenos);
hbox.setAlignment(Pos.CENTER);
vbox.setAlignment(Pos.CENTER);
setGraphic(vbox);
} else {
setGraphic(null);
}
}
};
});
In the handle() method you can do
Object row = getTableView.getItems().get(getIndex());
You can replace Object with a more specific type if you use more specific types throughout in the type parameters.

Clickhandler doesn't fire

I have a problem with ClickHandler in my project using GWT.
In the title of dialog box I want to insert a new button.
I created a new insert method: addToTitle(...).
I added ClickHandler to the button
Problem: click event by button doesn't fire. Why?
Here is my code:
DialogBox dialog = new DialogBox();
Button button = new Button("A new Button");
button.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event)
{
Window.alert("yuhuhuhu");
}
});
dialog.addToTitle(button);
code (extracted from the comments section) :
public class PlentyDialogWindow extends DialogBox {
private FlowPanel captionPanel = new FlowPanel();
public Widget closeWidget = null;
private boolean closeOnEscKey = false;
private FlowPanel titleContentWrapper = new FlowPanel();
public PlentyDialogWindow(boolean isModal) {
super( false, isModal);
this.addStyleName("DialogBox");
this.getElement().setId("DialogBoxId");
this.setAnimationEnabled(true);
this.closeWidget = generateCloseButton();
}
public void setCaption( String txt,Widget w) {
captionPanel.setWidth("100%");
this.addCaption(txt);
this.titleContentWrapper.getElement().getStyle().setDisplay(Display.INLINE_BLOCK);
captionPanel.add(this.titleContentWrapper);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.add(w);
widgetWrapper.addStyleName("PlentyPopupCloseIconWrapper");
captionPanel.add(widgetWrapper);
captionPanel.addStyleName("Caption");
Element td = getCellElement(0,1);
td.setInnerHTML("");
td.appendChild(captionPanel.getElement());
}
/** * * #param w */ public void addToTitle(Widget w) {
this.titleContentWrapper.add(w);
}
}
If your only problem is ClickHandler not being called try using addDOMHandler instead of addClickHandler
yourWidget.addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
}
},ClickEvent.getType());
The solution is a bit tricky.
public class PlentyDialogWindow extends DialogBox {
/*
* Create custom inner class extending `FlowPanel`. You need it only
* to make `onAttach` and `onDetach` methods be visible to wrapping
* class (e.g. your `PlentyDialogWindow` class).
*/
static class MyCaptionPanel extends FlowPanel {
#Override
protected void onAttach() {
super.onAttach();
}
#Override
protected void onDetach() {
super.onDetach();
}
}
/*
* `PlentyDialogWindow`'s field `captionPanel` will be an instance of
* this class.
*/
private MyCaptionPanel captionPanel = new MyCaptionPanel();
/*
* ... leave the rest of your class untouched ...
*/
/*
* Finally, overwrite `PlentyDialogWindow`'s `onAttach` and `onDetach`
* methods to invoke `captionPanel`'s corresponding methods:
*/
#Override
protected void onAttach() {
super.onAttach();
captionPanel.onAttach();
}
#Override
protected void onDetach() {
super.onDetach();
captionPanel.onDetach();
}
}
That's all.

Categories

Resources