JavaFX getChildren().addAll() KeyEvent Doesn't detect after buttons added - button

Im trying to add Buttons to my Game. Before i added the Buttons on the BaseScene Constructor, the KeyEvent worked very well in the game Method in the class GamePlay. After i added this Line of Code in the BaseScene: root.getChildren().addAll(canvas, buttonDown, buttonUp, buttonLeft, buttonRight);, the keyEvent didnt detect anymore. So i dont know why the buttons affect the keyEvent in this case.
BaseScene:
public abstract class BaseScene extends Scene {
protected Navigator navigator;
protected KeyEventHandler keyEventHandler = new KeyEventHandler();
protected Image backgroundImage;
protected Canvas canvas;
protected GraphicsContext gc;
protected static Group root;
protected Button buttonUp = new Button();
protected Button buttonLeft = new Button();
protected Button buttonRight = new Button();
protected Button buttonDown = new Button();
protected ImageView buttonViewUp;
protected ImageView buttonViewDown;
protected ImageView buttonViewRight;
protected ImageView buttonViewLeft;
public BaseScene(Group root, int height, int width, Navigator navigator){
super(root);
canvas = new Canvas(width * 89, height * 89);
gc = this.canvas.getGraphicsContext2D();
this.navigator = navigator;
this.setOnKeyPressed(keyEventHandler);
this.setOnKeyReleased(keyEventHandler);
buttonViewDown = new ImageView(String.valueOf(getClass().getResource("/buttonDown.png")));
buttonViewLeft = new ImageView(String.valueOf(getClass().getResource("/buttonLeft.png")));
buttonViewRight = new ImageView(String.valueOf(getClass().getResource("/buttonRight.png")));
buttonViewUp = new ImageView(String.valueOf(getClass().getResource("/buttonUp.png")));
buttonViewDown.setFitWidth(50);
buttonViewDown.setFitHeight(50);
buttonViewLeft.setFitHeight(50);
buttonViewLeft.setFitHeight(50);
buttonViewRight.setFitHeight(50);
buttonViewRight.setFitHeight(50);
buttonViewUp.setFitHeight(50);
buttonViewUp.setFitHeight(50);
buttonUp.setStyle("-fx-background-color: transparent");
buttonUp.setGraphic(buttonViewUp);
buttonUp.toFront();
buttonLeft.setStyle("-fx-background-color: transparent");
buttonLeft.setGraphic(buttonViewLeft);
buttonLeft.toFront();
buttonRight.setStyle("-fx-background-color: transparent");
buttonRight.setGraphic(buttonViewRight);
buttonRight.toFront();
buttonDown.setStyle("-fx-background-color: transparent");
buttonDown.setGraphic(buttonViewDown);
buttonDown.toFront();
root.getChildren().addAll(canvas, buttonDown, buttonUp, buttonLeft, buttonRight);
}
public void draw() {
gc.drawImage(backgroundImage, 0, 0);
}
}
GamePlay:
public class GamePlay extends BaseScene {
private Controller controller = new Controller();
private GameBoard gameBoard = new GameBoard();
private KeyEventHandler keyEventHandler = new KeyEventHandler();
private ScheduledExecutorService ec = Executors.newSingleThreadScheduledExecutor(); //is used for shoot Delays
private AnimationTimer animationTimer = new AnimationTimer() {
#Override
public void handle(long currentTimeInNanoSec) {
}
};
public GamePlay(Navigator navigator) throws IOException, URISyntaxException {
super(new Group(), 10, 10, navigator);
game();
this.setOnKeyReleased(keyEventHandler);
animationTimer.start();
}
private void game() throws IOException {
try{
gameBoard.setBoard(gameBoard.buildMap());
} catch (URISyntaxException e){
setOnKeyPressed(keyEvent -> {
navigator.navigateTo(Scenes.GAMEWIN);
});
}
this.setOnKeyPressed(event -> {
switch (event.getCode()) {
case UP -> {
try {
controller.move(gc, gameBoard, 0, -1);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
case DOWN -> {
try {
controller.move(gc, gameBoard, 0, 1);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
case LEFT -> {
try {
controller.move(gc, gameBoard, -1, 0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
case RIGHT -> {
try {
controller.move(gc, gameBoard, 1, 0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
try {
gameBoard.drawMap(gc, gameBoard.getBoard());
} catch (Exception e) {
throw new RuntimeException(e);
}
detectWinOrLoose();
});
this.setOnKeyReleased(event -> {
detectWinOrLoose();
});
this.buttonDown.setOnAction(event -> {
try {
controller.move(gc, gameBoard, 0, 1);
} catch (Exception e) {
throw new RuntimeException(e);
}
buttonUp.setLayoutY(gameBoard.getY() * 89 - 89 );
buttonUp.setLayoutX(gameBoard.getX() * 89);
buttonLeft.setLayoutX(gameBoard.getX() * 89 - 89);
buttonLeft.setLayoutY(gameBoard.getY() * 89);
buttonRight.setLayoutX(gameBoard.getX() * 89 + 89);
buttonRight.setLayoutY(gameBoard.getY() * 89);
buttonDown.setLayoutY(gameBoard.getY() * 89 + 89);
buttonDown.setLayoutX(gameBoard.getX() * 89);
try {
gameBoard.drawMap(gc, gameBoard.getBoard());
} catch (Exception e) {
throw new RuntimeException(e);
}
detectWinOrLoose();
});
this.buttonUp.setOnAction(event -> {
try {
controller.move(gc, gameBoard, 0, -1);
} catch (Exception e) {
throw new RuntimeException(e);
}
buttonUp.setLayoutY(gameBoard.getY() * 89 - 89 );
buttonUp.setLayoutX(gameBoard.getX() * 89);
buttonLeft.setLayoutX(gameBoard.getX() * 89 - 89);
buttonLeft.setLayoutY(gameBoard.getY() * 89);
buttonRight.setLayoutX(gameBoard.getX() * 89 + 89);
buttonRight.setLayoutY(gameBoard.getY() * 89);
buttonDown.setLayoutY(gameBoard.getY() * 89 + 89);
buttonDown.setLayoutX(gameBoard.getX() * 89);
try {
gameBoard.drawMap(gc, gameBoard.getBoard());
} catch (Exception e) {
throw new RuntimeException(e);
}
detectWinOrLoose();
});
this.buttonLeft.setOnAction(event -> {
try {
controller.move(gc, gameBoard, -1, 0);
} catch (Exception e) {
throw new RuntimeException(e);
}
buttonUp.setLayoutY(gameBoard.getY() * 89 - 89 );
buttonUp.setLayoutX(gameBoard.getX() * 89);
buttonLeft.setLayoutX(gameBoard.getX() * 89 - 89);
buttonLeft.setLayoutY(gameBoard.getY() * 89);
buttonRight.setLayoutX(gameBoard.getX() * 89 + 89);
buttonRight.setLayoutY(gameBoard.getY() * 89);
buttonDown.setLayoutY(gameBoard.getY() * 89 + 89);
buttonDown.setLayoutX(gameBoard.getX() * 89);
try {
gameBoard.drawMap(gc, gameBoard.getBoard());
} catch (Exception e) {
throw new RuntimeException(e);
}
detectWinOrLoose();
});
this.buttonRight.setOnAction(event -> {
try {
controller.move(gc, gameBoard, 1, 0);
} catch (Exception e) {
throw new RuntimeException(e);
}
buttonUp.setLayoutY(gameBoard.getY() * 89 - 89 );
buttonUp.setLayoutX(gameBoard.getX() * 89);
buttonLeft.setLayoutX(gameBoard.getX() * 89 - 89);
buttonLeft.setLayoutY(gameBoard.getY() * 89);
buttonRight.setLayoutX(gameBoard.getX() * 89 + 89);
buttonRight.setLayoutY(gameBoard.getY() * 89);
buttonDown.setLayoutY(gameBoard.getY() * 89 + 89);
buttonDown.setLayoutX(gameBoard.getX() * 89);
try {
gameBoard.drawMap(gc, gameBoard.getBoard());
} catch (Exception e) {
throw new RuntimeException(e);
}
detectWinOrLoose();
});
}
private void detectWinOrLoose() {
if (controller.isEveryChestOnTarget(gameBoard.getBoard())) {
gameBoard.setLevel(gameBoard.getLevel() + 1);
try {
gameBoard.setBoard(gameBoard.buildMap());
gameBoard.drawMap(gc, gameBoard.getBoard());
controller.setGameOver(false);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (URISyntaxException e) {
setOnKeyPressed(keyEvent -> {
navigator.navigateTo(Scenes.GAMEWIN);
});
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
game();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (controller.isGameOver()) {
try {
gameBoard.setBoard(gameBoard.buildMap());
controller.setGameOver(false);
} catch (IOException e) {
setOnKeyPressed(keyEvent -> {
navigator.navigateTo(Scenes.GAMEWIN);
});
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
game();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
gameBoard.drawMap(gc, gameBoard.getBoard());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

Related

SignalR Java Client not working in Android 12

I implemented SignalR Java Client in my Android Project. It works well on Android Versions 6 to 11 but fails on Android 12, I'm getting this error only on Android 12 java.net.SocketException: Socket closed [Ljava.lang.StackTraceElement;#e95116d, here is my code:
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.OnClosedCallback;
import org.json.JSONObject;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import timber.log.Timber;
public class SignalRChatService {
Timer timer = new Timer();
public void startTimer()
{
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Your code here
Timer_Elapsed();
}
}, 1000, 2000);
}
private void Timer_Elapsed()
{
try
{
module.checkNetwork(context);
if(!Connected)
{
Init();
}
}
catch (Exception e)
{
Connected = false;
}
}
private HubConnection _connection;
public boolean Connected;
public String instanceName;
public int instanceProfileId;
private boolean connecting;
private SignalRMessageReceivedEvents signalRMessageReceivedEvents;
private final Gson gson;
private final Context context;
public SignalRChatService(Context context, String instanceName, int instanceProfileId, SignalRMessageReceivedEvents signalRMessageReceivedEvents) {
this.instanceName = instanceName;
this.instanceProfileId = instanceProfileId;
this.connecting = false;
this.context = context;
this.signalRMessageReceivedEvents = signalRMessageReceivedEvents;
gson = new GsonBuilder().setPrettyPrinting().create();
}
public void Stop()
{
try
{
_connection.stop();
}
catch(Exception ignored)
{}
}
public void Init()
{
if (connecting)
{
return;
}
try
{
connecting = true;
_connection = HubConnectionBuilder.create("https://" + instanceName.trim().toLowerCase() + ".com").build();
try
{
_connection.start();
Connected = true;
}
catch (Exception e)
{
Connected = false;
Timber.e("SignalR Push connect: %s", e.getLocalizedMessage());
return;
}
_connection.on("Message", (message) ->
{
try
{
// Separate this code affterwads
JSONObject messageObject = new JSONObject(message);
String Messagetype = (String) messageObject.get("messageType");
HandleWebSocketMessage(Messagetype, message);
}
catch (Exception ignored)
{
}
}, String.class);
_connection.onClosed(new OnClosedCallback() {
#Override
public void invoke(Exception exception) {
handleClosed();
}
});
}
catch (Exception ignored)
{
}
finally
{
connecting = false;
startTimer();
}
}
private void handleClosed()
{
try
{
TimeUnit.MILLISECONDS.sleep(100);
}
catch (Exception ignored)
{
}
Init();
}
}
I've tried upgrading to the latest version of SignalR Java Client
implementation "com.microsoft.signalr:signalr:6.0.3"
and it is still not working. It just wont receive any Signal.

CTRL+C doesn't work while focus on TextField

Here is my code that set action for ctrl+c combination in JavaFX. It doesn't work when there is a focus on TextField command_line. Why?
public void setCtrlC() {
command_line.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY),
new Runnable() {
#Override
public void run() {
LOGGER.debug("CTRL+C pressed");
try {
if (tab_toradex.isSelected()) {
bw.write(3);
bw.flush();
}
if(tab_novatel.isSelected()){
bw2.write(3);
bw2.flush();
}
} catch (IOException e) {
LOGGER.debug("CTRL+C command failed");
}
}
});
}
Thanks!
Ok, solved with this:
final KeyCombination keyCombinationShiftC = new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_DOWN);
public void setCtrlC() {
command_line.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (keyCombinationShiftC.match(event)) {
LOGGER.debug("CTRL+C pressed");
try {
if (tab_toradex.isSelected()) {
bw.write(3);
bw.flush();
}
if(tab_novatel.isSelected()){
bw2.write(3);
bw2.flush();
}
} catch (IOException e) {
LOGGER.debug("CTRL+C command failed");
}
}
}
});
}
On the other hand, now it works only while TextField is focused...

Javafx Task - update progress from a method

In a JavaFX application I wish to update a status bar according to some work logic which I've implemented in an other class.
I can't figure out how to combine my desire to pass to work logic to the method (and not to write it inside the task) and to know about the work progress percentage.
This is an example of the controller with the Task:
public class FXMLDocumentController implements Initializable {
#FXML private Label label;
#FXML ProgressBar progressBar;
#FXML
private void handleButtonAction(ActionEvent event) {
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality.performWorkOnDb();
//updateProgress(1, 1);
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
progressBar.progressProperty().bind(myService.progressProperty());
myService.restart();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
This is the helper class:
public class DatabaseFunctionality {
public static void performWorkOnDb () throws InterruptedException {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
//Update progress
}
}
}
Thank you
You have a couple of options here. One is to do as Uluk suggests and expose an observable property in your DatabaseFunctionality class:
public class DatabaseFunctionality {
private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper();
public double getProgress() {
return progressProperty().get();
}
public ReadOnlyDoubleProperty progressProperty() {
return progress ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
progress.set(1.0*i / 100);
}
}
}
And now in your Task, you can observe that property and update the task's progress:
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.progressProperty().addListener((obs, oldProgress, newProgress) ->
updateProgress(newProgress.doubleValue(), 1));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
Another option (in case you don't want your data access object to depend on the JavaFX properties API) is to pass the data access object a callback to update the progress. A BiConsumer<Integer, Integer> would work for this:
public class DatabaseFunctionality {
private BiConsumer<Integer, Integer> progressUpdate ;
public void setProgressUpdate(BiConsumer<Integer, Integer> progressUpdate) {
this.progressUpdate = progressUpdate ;
}
public void performWorkOnDb() throws Exception {
for (int i = 1; i <= 100; i++) {
System.out.println("i=" + i);
Thread.sleep(100);
if (progressUpdate != null) {
progressUpdate.accept(i, 100);
}
}
}
}
and then
Service<Void> myService = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
try {
DatabaseFunctionality dbFunc = new DatabaseFunctionality();
dbFunc.setProgressUpdate((workDone, totalWork) ->
updateProgress(workDone, totalWork));
dbaseFunc.performWorkOnDb();
} catch (InterruptedException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
}
};
public void initialize() {
Task<Void> task = new Task<>() {
#Override
protected Void call() {
try {
Double d = 0.0;
for (int i = 1; i <= 100; i++) {
Thread.sleep(100);
d = 1.0 * i / 100;
updateProgress(d, 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
task.progressProperty().addListener((obs, oldProgress, newProgress) -> {
System.out.println((newProgress.doubleValue() * 100) + "% completed");
});
new Thread(task).start();
}

JavaFx - is there any way to refresh whole treeview?

I'm newbie on java fx.
And I'm making an application with treeview and treeview has made by nested set model. So each treeitem has to have left, right data.(I made a treeitem like Treeitem>. Object has data(id, label name, left, right, etc) and String is label name to be shown at treeview.)
The problem is that whole treeitems have to be updated when I add a new treeitem(or delete treeitem). I already implemented whole data(the other treeitem's) to be updated on DB, but treeview still has data isn't updated.
I looked for the way to refresh treeview, but I just found user shouldn't use updateitem forcefully.
Is there any way or method to refresh whole treeview?
FYI. code below
Pair<LabelTreeItem,String> f = new Pair<>(new LabelTreeItem(1, "Root", 0, 0, "",0), "Root");
try {
f = new Pair<>(service.getRoot(), "Root");
} catch (SQLException e) {
System.out.println("Can't find Root Node");
e.printStackTrace();
}
TreeItem<Pair<LabelTreeItem,String>> root = createNode(f);
root.setExpanded(true);
treeView.setRoot(root);
treeView.setEditable(true);
treeView.setCellFactory(new Callback<TreeView<Pair<LabelTreeItem,String>>,TreeCell<Pair<LabelTreeItem,String>>>(){
#Override
public TreeCell<Pair<LabelTreeItem,String>> call(TreeView<Pair<LabelTreeItem,String>> p) {
return new TextFieldTreeCellImpl();
}
});
.....................................
private TreeItem<Pair<LabelTreeItem,String>> createNode(final Pair<LabelTreeItem,String> f) {
return new TreeItem<Pair<LabelTreeItem,String>>(f) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;
#Override public ObservableList<TreeItem<Pair<LabelTreeItem,String>>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(this));
}
return super.getChildren();
}
#Override public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
Pair<LabelTreeItem,String> f = getValue();
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
if(nodeRight-nodeLeft == 1) {
isLeaf = true;
System.out.println("this is leaf");
}
}
return isLeaf;
}
private ObservableList<TreeItem<Pair<LabelTreeItem,String>>> buildChildren(TreeItem<Pair<LabelTreeItem,String>> TreeItem) {
Pair<LabelTreeItem,String> f = TreeItem.getValue();
System.out.println("ID: "+f.getKey().getId());
int nodeLeft = f.getKey().getLeft();
int nodeRight = f.getKey().getRight();
try {
if (f != null && nodeRight-nodeLeft != 1) {
ArrayList<LabelTreeItem> item = new ArrayList<>();
item = service.getChildren(f.getKey().getLeft(), f.getKey().getRight(), f.getKey().getDepth());
ArrayList<Pair<LabelTreeItem,String>> itemList = new ArrayList<>();
for(int i=0; i<item.size(); i++) {
System.out.println("test : " + item.get(i).getLabel());
Pair<LabelTreeItem,String> pair = createPair(item.get(i), item.get(i).getLabel());
itemList.add(pair);
}
if(itemList.size() != 0) {
ObservableList<TreeItem<Pair<LabelTreeItem,String>>> children = FXCollections.observableArrayList();
for (Pair<LabelTreeItem,String> childNode : itemList) {
children.add(createNode(childNode));
}
return children;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FXCollections.emptyObservableList();
}
};
}
private Pair<LabelTreeItem, String> createPair(LabelTreeItem item, String name) {
return new Pair<>(item, name);
}
LabelTreeItem.java
public class LabelTreeItem {
private int id;
private String label;
private int left;
private int right;
private String comment;
private int depth;
public LabelTreeItem(int id, String label, int left, int right, String comment, int depth) {
this.id = id;
this.label = label;
this.left = left;
this.right = right;
this.comment = comment;
this.depth = depth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getLeft() {
return left;
}
public void setLeft(int left) {
this.left = left;
}
public int getRight() {
return right;
}
public void setRight(int right) {
this.right = right;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public int getDepth() {
return depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
}
TextFieldTreeCellImpl.java
public TextFieldTreeCellImpl() {
service = SqliteService.getInstance();
MenuItem addLabel = new MenuItem("Label add");
addMenu.getItems().add(addLabel);
addLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
getTreeItem().setExpanded(true);
LabelTreeItem newItem = null;
try {
id = getTreeItem().getValue().getKey().getId();
label = getTreeItem().getValue().getKey().getLabel();
depth = getTreeItem().getValue().getKey().getDepth()+1;
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
newItem = service.getData("New Label", id,depth);
TreeItem<Pair<LabelTreeItem,String>> newLabel = new TreeItem(createPair(newItem, newItem.getLabel()));
getTreeItem().getChildren().add(newLabel);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
MenuItem editLabel = new MenuItem("Label modify");
addMenu.getItems().add(editLabel);
editLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
startEdit();
}
});
MenuItem removeLabel = new MenuItem("Label delete");
addMenu.getItems().add(removeLabel);
removeLabel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
left = getTreeItem().getValue().getKey().getLeft();
right = getTreeItem().getValue().getKey().getRight();
service.deleteData(left, right, (right-left)+1);
} catch (SQLException e) {
e.printStackTrace();
}
getTreeItem().getParent().getChildren().remove(getTreeItem());
System.out.println("Remove");
}
});
}
#Override
protected void updateItem(final Pair<LabelTreeItem, String> pair, boolean empty) {
super.updateItem(pair, empty);
if (!empty && pair != null) {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(pair.getKey().getLabel());
setGraphic(getTreeItem().getGraphic());
setContextMenu(addMenu);
}
} else {
setText(null);
setGraphic(null);
}
setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip(pair.getKey().getLabel());
tTip.uninstall(getTreeView(), tTip);
}
}
});
setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(pair !=null){
Tooltip tTip = new Tooltip();
tTip.setText(pair.getKey().getLabel()
+"\nComment : "+pair.getKey().getComment()
+"\nLeft : "+pair.getKey().getLeft()
+"\nRight : "+pair.getKey().getRight());
tTip.setFont(new Font("Arial", 16));
tTip.setStyle("-fx-background-color: grey;");
tTip.centerOnScreen();
tTip.install(getTreeView(), tTip);
}
}
});
}
DB Table
id|label|left|right|comment|depth

Fragments MediaPlayer and moving back

I've got an app with Navigation Drawer using fragments. From One of the fragments that lists all tracks, I try to run a media player and show it's associated lyrics. But I'm unable to handle the back button of this fragment.
What I have done here only navigates back to the previous fragment. But I'm unable to click the ListView items after coming back and I'm also unable to click on my nav drawer in the mediaplayer or once I move back from the mediaplayer fragment. Anyone with any ideas?
Here's my code:
package com.myapp.slidingmenu;
import java.io.IOException;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.Toast;
import com.myapp.myplayer.R;
public class PlayTrackFragment extends Fragment implements MediaPlayerControl {
protected static final Fragment PlayTrackFragment = null;
public PlayTrackFragment(){}
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
AssetFileDescriptor fd = null;
int iDispatchCounter = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_playtrack, container, false);
Bundle args = getArguments();
if (args != null && args.containsKey("id_User"))
{
String userId = args.getString("id_User");
Toast.makeText(rootView.getContext(),userId,Toast.LENGTH_SHORT).show();
}
WebView wv;
wv = (WebView) rootView.findViewById(R.id.webViewPlayTrack);
wv.loadUrl("file:///android_asset/traditions.html");
wv.setBackgroundColor(0x00000000);
wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
//AssetFileDescriptor fd = expansionFile.getAssetFileDescriptor(mytracks[trackTitle].toString()+".mp3");
AssetFileDescriptor fd = null;
try {
fd = getActivity().getAssets().openFd("aa01.mp3");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (fd == null)
{
Toast.makeText(rootView.getContext(), "Expansion File Not Loaded", Toast.LENGTH_SHORT).show();
//return;
}
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(rootView.getContext()){
#Override
public void hide() {
this.show(0);
}
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && iDispatchCounter == 1)
{
iDispatchCounter++;
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
if(mMediaPlayer.isPlaying()){ mMediaPlayer.pause();}
//mMediaPlayer = null;
//mMediaController.hide();
mMediaController.setVisibility(View.GONE);
mMediaController = null;
HomeFragment homefragment = new HomeFragment();
PlayTrackFragment playtrackfragment = new PlayTrackFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, homefragment).commit();
fragmentTransaction2.remove(playtrackfragment).commit();
//fragmentTransaction.commit();
//mMediaPlayer.stop();
//mMediaPlayer = null;
//mMediaController = null;
//getActivity().finish();
//getActivity().onBackPressed();
//Todo: make finish work
//return true;
//Toast.makeText(rootView.getContext(),"Inside onDispatchKey",Toast.LENGTH_SHORT).show();
Log.i((String) getTag(), "onDispatch keyCode: " + event);
//getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getFragmentManager().popBackStackImmediate();
return false;
}
return false;
}
};
//Original Lines
//mMediaController.setMediaPlayer(PlayTrack.this);
mMediaController.setBackgroundColor(Color.rgb(40, 40, 80));
mMediaController.setMediaPlayer(PlayTrackFragment.this);
mMediaController.setAnchorView(rootView.findViewById(R.id.layoutPlayTrack));
mMediaPlayer.setVolume(1f, 1f);
try {
mMediaPlayer.setDataSource( fd.getFileDescriptor(), fd.getStartOffset(),fd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
getActivity().setVolumeControlStream(AudioManager.STREAM_SYSTEM);
mMediaPlayer.start();
mMediaController.show(0);
}
});
}
});
/*rootView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_MOVE){
//mMediaController.show();
//do something
}
return true;
}
});*/
/*rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
rootView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Toast.makeText(rootView.getContext(),"Inside onKey",Toast.LENGTH_SHORT).show();
Log.i(getTag(), "onKey keyCode: " + keyCode);
if( keyCode == KeyEvent.KEYCODE_BACK ) {
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return true;
} else {
return false;
}
}
});*/
return rootView;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
if (mMediaPlayer != null){return mMediaPlayer.getCurrentPosition();}
return 0;
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
I found a solution. I can hide the MediaController in the onDetach of the fragment.
#Override
public void onDetach() {
// TODO Auto-generated method stub
mMediaController.hide();
super.onDetach();
}
But there is still one problem. Although I can pull out my sliding drawer menu, I cannot click it. The MediaController seems to be on top of everything. How can I fix this please?

Resources