MouseClick on Label - events

I am trying to register a click on a label, but i can't get it to work.
So far I've tried to set the SelectionAdapter to the label but click-events aren't fired.

Labels are not selectable Controls SelectionAdapter won't work for it. Try adding a MouseListener.

For sake of completeness, I'll just add this code sample:
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseUp(MouseEvent event) {
super.mouseUp(event);
if (event.getSource() instanceof Label) {
Label label = (Label)event.getSource();
System.out.println("Label was clicked: " + label.getText());
}
}
});

Related

Radio Button Change Event JavaFx

i have a lot of HBoxes with some different components inside ( RadioButton, Labels, Buttons ...).
The RadioButtons are in a ToggleGroup, so only 1 Radio Button can be selected.
I want to add a OnChange - Event to the Radio Button. If the RadioButton would be unselected there should be a Event-Trigger. How can i add the Event to the Radio-Button?
At the moment i have a code like this, but it doesn't have the function i want to have.
radio.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
if(!radio.isSelected()){
ivTriangleImg.setRotate(iRotateCoord2);
btnTriangle.setGraphic(ivTriangleImg);
}
if(group!=null){
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
#Override
public void changed(
ObservableValue<? extends Toggle> arg0,
Toggle arg1, Toggle arg2) {
}
});
}
}
});
I use JavaFX 2.0 and Java 1.7 so i can not use Lambda Functions or the special component functions of JavaFx8 / Java 1.8
The state of JavaFX controls is represented by observable properties. You can access these properties with control.propertyNameProperty() and add ChangeListeners to them:
radioButton.selectedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> obs, Boolean wasPreviouslySelected, Boolean isNowSelected) {
if (isNowSelected) {
// ...
} else {
// ...
}
}
});
radio.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
if(!radio.isSelected()){
ivTriangleImg.setRotate(iRotateCoord2);
btnTriangle.setGraphic(ivTriangleImg);
}
if(group!=null){
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
#Override
public void changed(
ObservableValue<? extends Toggle> arg0,
Toggle arg1, Toggle arg2) {
if(!radio.isSelected()&&ivTriangleImg.getRotate()!=iRotateCoord1){
ivTriangleImg.setRotate(iRotateCoord1);
btnTriangle.setGraphic(ivTriangleImg);
}
}
});
}
}
});
This would work for my Question. I have done a little mistake, so i don't check the Radio-Style. It works fine now... Sorry for this Question.
Is there a possibility to check the Event at the Radio Button and not at his group?
In case you have many radio buttons you dont want have a single EventHandlers for each one of them....
Here is an example with 6 radio buttons but just one ChangeListener where the events are all process in a centralized method.
This detects programatic events, keyboard events and mouse events
Note that the listener is added to the ToggleGroup
public class ReportOptionsPane extends BorderPane implements ChangeListener<Toggle> {
RadioButton radioFoldersOnly ;
RadioButton radioAllItems ;
RadioButton radioArtifactsOnly ;
RadioButton radioStatsOrderByOccurrence ;
RadioButton radioStatsOrderByName ;
public ReportOptionsPane(ReportOptions rep) {
super() ;
ToggleGroup tg = new ToggleGroup();
radioFoldersOnly = new RadioButton("Folders only") ;
radioAllItems = new RadioButton("Files & Folders") ;
radioArtifactsOnly = new RadioButton("Artifacts only") ;
radioFoldersOnly.setToggleGroup(tg);
radioAllItems.setToggleGroup(tg);
radioArtifactsOnly.setToggleGroup(tg);
//You add the listener to the toogle group of your radio buttons
tg.selectedToggleProperty().addListener(this);
ToggleGroup tg2 = new ToggleGroup();
radioStatsOrderByOccurrence = new RadioButton("Order stats by occurrence") ;
radioStatsOrderByName = new RadioButton("Order stats by name") ;
radioStatsOrderByOccurrence.setToggleGroup(tg2);
radioStatsOrderByName.setToggleGroup(tg2);
//You can reuse the listener for the second toogle group of your radio buttons
tg2.selectedToggleProperty().addListener(this);
}
//Then you handle all in a centralized place
#Override
public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {
if(newValue.equals(radioFoldersOnly)) {
//react to radio button being selected
} else if(newValue.equals(radioAllItems)) {
//react to radio button being selected
} else if(newValue.equals(radioArtifactsOnly)) {
//react to radio button being selected
} else if(newValue.equals(radioStatsOrderByName)) {
//react to radio button being selected
} else if(newValue.equals(radioStatsOrderByOccurrence) {
//react to radio button being selected
}
}
}

Prevent selection of Tree Cell from right-click on Tree View Cell

I'm developing a custom TreeView object.
I'm using a custom cellFactory to provide the TreeCell objects of my TreeView.
This allows me to install custom Context Menu on the various cells, depending on the Item they are displaying.
But I'm not entirely satisfied with the behaviour.
When left-clicking on cell, it gets selected (OK)
But when right-clicking a cell, the context menu is displayed (OK) but the cell is also selected. (NOK)
How can I change this behaviour ?
I tried to implement an eventFilter on the tree view, to consume the event if it is a right-click but this doesn't change anything, the above behaviour still applies.
addEventFilter(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.SECONDARY) {
event.consume();
}
}
});
setCellFactory(new Callback<TreeView<TreeDisplayable>, TreeCell<TreeDisplayable>>() {
#Override
public TreeCell<TreeDisplayable> call(
final TreeView<TreeDisplayable> treeView) {
return new TreeDisplayableTreeCell(owner, javaModel);
}
});
public class TreeDisplayableTreeCell extends TreeCell<TreeDisplayable> {
...
#Override
public void updateItem(TreeDisplayable item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setText(getItem().treeViewString());
setGraphic(item.getPic());
if (getTreeItem().getParent() == null) {
// it means it's the root node
setContextMenu(new RootItemContextMenu(javaModel, owner));
} else {
setContextMenu(new TreeItemContextMenu(javaModel, owner,getTreeItem().getValue()));
}
}
}
}
Reacting on Tony's comment
Creating a custom EventDispatcher does the trick.
public class TreeEventDispatcher implements EventDispatcher {
#Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
if (event instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) event;
if (mouseEvent.getButton() == MouseButton.SECONDARY) {
event.consume();
} else {
event = tail.dispatchEvent(event);
}
} else {
event = tail.dispatchEvent(event);
}
return event;
}
}
The behaviour is identical for all events, except the right click event, which is consumed, thus preventing the right-click selection of any TreeCell.
Luckily enough, the context menu is still displayed on right click (although I don't understand why ...) Does anybody have a clue ?
Previous Facewindu answer is actually working, but there is another way to achieve that behavior and still have context menu appearing on right click:
treeView.addEventFilter(MOUSE_PRESSED, event -> {
if (event.isSecondaryButtonDown()) {
Node text = (Node) event.getTarget();
TreeCell<...> treeCell = (TreeCell<...>) text.getParent();
treeCell.getContextMenu().show(treeCell, 0, 0);
event.consume();
}
});

Hide and Show Textview with button click in Dialog fragment

I am new to programming and i hope someone can help provide me a simple code
I have a dialog fragment with a textview and a button.
It loaded with both visible.
when I click on the button, I need to hide the textview.
when I click it again, I need the textview to be shown.
I tried textview1.setVisibility(View.GONE);
The textview still stays there, i think i am missing a refresh method???
Thanks
btnclick.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textview1.setVisibility(View.GONE);
}
});
Hi, Use if else loop it will solve this issue for example refer this code
boolean s=true;
btnclick.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(s) {
textview1.setVisibility(View.GONE);
s=false;
}
else {
textview1.setVisibility(View.VISIBLE);
s=true;
}
} });

javafx HTMLEditor scrollpane scrolls on Space Key

I have a VBox inside a ScrollPane wich contains a HTMLEditor and other stuff.
When I type text inside the HTMLEditor each time I hit the Space Bar, I get a whitespace inside the editor as expected but also the Scrollpane scrolls down. First I worked around this by adding a EventFilter to the Scrollpane and consume the KEY_PRESSED event. But now I need this event inside the HTMLEditor.
So my question: is there any Flag to tell the Scrollpane not to scroll on KeyCode.SPACE or is there a way to route the input Focus/ Key Events only to the HTMLEditor, bypassing the Scrollpane? Or a way to filter this event only on the Scrollpane?
You can reproduce this also with javafx Scene Builder:
Scrollpane->VBox(larger than Scrollpane so Scrollbars appear)->2*HTMLEditor, Preview in Window, hit the Space Bar.
Solved:
Added an EventFilter to the HTMLEditor, which consumes the KeyCode.SPACE on KEY_PRESSED.
htmlEditor.addEventFilter( KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getEventType() == KeyEvent.KEY_PRESSED){
// Consume Event before Bubbling Phase, -> otherwise Scrollpane scrolls
if ( event.getCode() == KeyCode.SPACE ){
event.consume();
}
}
}
});
I just ran into a similar problem. What I did was to pass the filtered event on to my event handler method directly before consuming it. For your case, it would look something like this (assume you have an KeyEvent handler method that you've named onKeyPressed()):
htmlEditor.setOnKeyPressed(new EventHandler<KeyEvent>() {#Override public void handle(KeyEvent t) { onKeyPressed(t); }});
scrollPane.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if(t.getCode() == KeyCode.SPACE) {
onKeyPressed(t);
t.consume();
}
}
});
Create your own widget that extends the HTMLEditor and add a listener for the pressed event.
setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.SPACE
|| event.getCode() == KeyCode.TAB ) {
// Consume Event before Bubbling Phase, -> otherwise Scrollpane scrolls
event.consume();
}
});

javafx, TableView: detect a doubleclick on a cell

Given a TableView, i need to detect the doubleclick on a cell.
tableView.setOnMouseClicked(new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent event)
{
if(event.getClickCount()>1)
{
System.out.println("double clicked!");
}
}
});
How to determine the cell on which the mouse has been clicked?
Code example.
Run the "Example 12-11: Alternative Solution Of Cell Editing" of official tableview tutorial.
Replace the followings:
table.setEditable(false);
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
TableCell cell = new TableCell<Person, String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() > 1) {
System.out.println("double clicked!");
TableCell c = (TableCell) event.getSource();
System.out.println("Cell text: " + c.getText());
}
}
});
return cell;
}
};
No need to EditingCell since your cells are uneditable. Cell factory is used for cell rendering. So one can put any node/control other than default Labeled using cell's setGraphics() method. IMO you cannot access the default cell directly so you should define your own cell factory to be able to put event filter on cell.
JavaFX allows you to set up multiple listeners per cell (I'm not saying that this is good or bad, just that you can). Each listener will execute your code if you have code set to execute a response to the specific listener for the specific column/row. To capture cell mouse clicks, I use the following:
table.setEditable(true);
table.getSelectionModel().setCellSelectionEnabled(true); // selects cell only, not the whole row
table.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent click) {
if (click.getClickCount() == 2) {
#SuppressWarnings("rawtypes")
TablePosition pos = table.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
int col = pos.getColumn();
#SuppressWarnings("rawtypes")
TableColumn column = pos.getTableColumn();
String val = column.getCellData(row).toString(); System.out.println("Selected Value, " + val + ", Column: " + col + ", Row: " + row);
if ( col == 2 ) { ... do something ... }
if ( col == 5 ) { ... do something ... }
if ( col == 6 ) { ... do something ... }
if ( col == 8 ) { ... do something ... }
}
}
});
You can see from the above code, on the columns I want to do something based on a mouse click, I have code:
if ( col == <int> ) { ... do something ... }
I also have those columns set to not allow editing:
thisCol.setEditable(false);
The rows that I want to edit I have .setEditable(true) but don't have a response included with a mouse click.
Cell editing defaults to 2 mouse clicks. You can change the above code to capture different mouse events on a cell, so you can still edit the cell with 2 mouse clicks, or open a URL, dialog box, etc., with any other mouse event determined by you. TableView allows you to determine your own functionality based on your imagination and programming skills. You're not stuck with "I can either edit it, or fire a mouse event with it." You can do both :)
Add the following in the body of your listener, with T the type of your table record :
#SuppressWarnings("rawtypes")
ObservableList<TablePosition> cells = tableView.getSelectionModel().getSelectedCells();
for( TablePosition< T, ? > cell : cells )
{
System.out.println( cell.getColumn());
}// for
Create your cell using a cell factory and in the cell factory which creates the cell node, place an mouse event handler or filter on the node rather than the tableView.
In my case i use next code
tableViewObject.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
if (t.getClickCount() == 2 && getSelectedItem() != null) {
SMPBLogger.logInfo("Double cliked", Boolean.TRUE);
if (listener != null) {
listener.doubleClicked(tableViewObject.this,getSelectedItem());
}
}
}
});

Resources