AndEngine ButtonSprite with single TextureRegion - java

I have a game that uses ButtonSprite as some of the UI element sprites.
For each button I have a Texture Region for Normal and Pressed States.
mSomeBottonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mLoadTextureAtlas, this, "SomeBotton.png", 0, 0);
mSomeBottonPressedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mLoadTextureAtlas, this, "SomeBottonPressed.png", 0, 0);
ButtonSprite someButtonSprite = new ButtonSprite(0, 0, mSomeBottonTextureRegion, mSomeBottonPressedTextureRegion, mEngine().getVertexBufferObjectManager());
I see there are no constructors that handle a ButtonSprite with a single TiledTextureRegion for which you can supply a different tile for each state.
Am I missing something? Is there a way to do this with ButtonSprite? Or will I have to Extend a TiledSprite and add button functionality so that I only have to make one TextureRegion instead of two.
Thanks

You can just supply a TiledTextureRegion to the ButtonSprite as it is designed to handle 3 states - normal, pressed, and disabled. Check the ButtonSprite.java and you will see several alternate constructors that take a TiledTextureRegion and set the stateCount to the number of tiles in the TiledTextureRegion passed in.
Here's one of those constructors
public ButtonSprite(final float pX, final float pY, final ITiledTextureRegion pTiledTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager, final OnClickListener pOnClickListener) {
super(pX, pY, pTiledTextureRegion, pVertexBufferObjectManager);
this.mOnClickListener = pOnClickListener;
this.mStateCount = pTiledTextureRegion.getTileCount();
switch(this.mStateCount) {
case 1:
Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.PRESSED + ".");
case 2:
Debug.w("No " + ITextureRegion.class.getSimpleName() + " supplied for " + State.class.getSimpleName() + "." + State.DISABLED + ".");
break;
case 3:
break;
default:
throw new IllegalArgumentException("The supplied " + ITiledTextureRegion.class.getSimpleName() + " has an unexpected amount of states: '" + this.mStateCount + "'.");
}
this.changeState(State.NORMAL);
}

Related

osmdroid: messed up tiles shown when loading custom tilesource

I try to show tiles from my custom tileserver.
I'm using my own tileserver (shown at https://www.url.be)
Tiles are shown correct here.
I just don't understand why my tiles are messed up on the android studio app (using osmdroid). The problem persists when zooming in too.
See this screenshot
And my code:
map = (MapView) findViewById(R.id.map);
// Create a custom tile source
map.setTileSource(new OnlineTileSourceBase("hot", 1, 20, 256, ".png",
new String[] { "https://www.url.be/hot/" }) {
#Override
public String getTileURLString(long pMapTileIndex) {
return getBaseUrl()
+ MapTileIndex.getZoom(pMapTileIndex)
+ "/" + MapTileIndex.getY(pMapTileIndex)
+ "/" + MapTileIndex.getX(pMapTileIndex)
+ mImageFilenameEnding;
}
});
//map.setTileSource(TileSourceFactory.MAPNIK);
map.setMultiTouchControls(true);
IMapController mapController = map.getController();
mapController.setZoom(15.0);
GeoPoint startPoint = new GeoPoint(51.111500, 3.985040);
mapController.setCenter(startPoint);
Any advice on this?
So, I have been looking further on this issue.
I had to switch the getY and getX in the code.
So:
return getBaseUrl()
+ MapTileIndex.getZoom(pMapTileIndex)
+ "/" + MapTileIndex.getY(pMapTileIndex)
+ "/" + MapTileIndex.getX(pMapTileIndex)
+ mImageFilenameEnding;
Had was wrong and should be:
return getBaseUrl()
+ MapTileIndex.getZoom(pMapTileIndex)
+ "/" + MapTileIndex.getX(pMapTileIndex)
+ "/" + MapTileIndex.getY(pMapTileIndex)
+ mImageFilenameEnding;
Hope this helps anyone

getInt Function Doesn't Return Anything

I am currently trying to making a custom rules plugin (for minecraft) and I am trying to see if the player has something activated which I stored in the config file. It is in the listener class (which calls the config from the main). Here is my code:
#EventHandler
public void onEvent(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (config.getInt("EditingLine." + player.getName().toLowerCase()) == 1) {
int line = 0;
try {
line = Integer.parseInt(e.getMessage());
} catch (Exception b) {
player.sendMessage(ChatColor.RED + "Invalid Number.");
config.set("EditingLine." + player.getName().toLowerCase(), 0);
}
if (!(line == 0)) {
config.set("EditingLine." + player.getName().toLowerCase(), 0);
config.set("EditingText." + player.getName().toLowerCase(), 1);
e.setCancelled(true);
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.GOLD + "Custom Rules" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enter the text you would now like on that line.");
}
}
}
The, config.getInt() function in the if then statement currently returns nothing. This may be happening because the config in the Listener Class is actually calling a custom made config, called 'playerdata.yml' and not the actual 'config.yml'. If there is any easier way to write this script, also let me know. I'm trying to make this as simple as I can.
The answer has been solved by merging my two configuration files together.

setGraphic() not working correctly on recursively created TreeItems

I'm writing a folder synchronization app. Currently, I'm working on the part responsible for recursively going through the two user-specified directory structures, comparing the folders and files in them to the other structure, and displaying whether each file or folder is unchanged, changed, or new, by means of a colored dot. The problem is that the program in its current state, while evaluating the relation correctly, only displays the dot on one TreeItem per dot color instead on all of them. Pic for reference:
Whats causing this? I have a suspicion that it has to do with the way object assignment works in Java, so I'm reassigning one and the same object somehow to all the proper TreeItems, only stopping at the last one, but that's too broad to work with. See the offending function below.
private void compareAndFillInSourceTreeView(Path x, TreeItem root) throws IOException {
String xSourceName = x.getName(x.getNameCount() - 1).toString();
String xTargetName = (getEquivalentFileInTarget(x).getName(getEquivalentFileInTarget(x).getNameCount() - 1))
.toString();
System.out.println("-----------------------------------------------------------------------------------------");
System.out.println("NEW CALL: " + x.toString() + " " + root);
System.out.println("EQUIVALENT: " + getEquivalentFileInTarget(x) + " EXISTS: " +
getEquivalentFileInTarget(x).toFile().exists());
System.out.println("IS NEW: " + xTargetName + ", " + (xTargetName == null));
System.out.println("UNCHANGED: " + x + " " + getEquivalentFileInTarget(x) + " NAMES: " + xSourceName + ", "
+ xTargetName);
System.out.println("CHANGED: " + ((x.getName(x.getNameCount() - 1)) ==
getEquivalentFileInTarget(x).getName(getEquivalentFileInTarget(x).getNameCount() - 1)));
if (x.toFile().isFile()) {
System.out.println("THIS IS A FILE: " + x.toString());
//if new, i.e. doesn't exist in the target
if (!getEquivalentFileInTarget(x).toFile().exists()) {
System.out.println("EQUIVALENT DOESN'T EXIST FOR THIS FILE IN TARGET");
TreeItem newBranch = makeBranch(xSourceName, root);
newBranch.setGraphic(blueDotIcon);
}
//if unchanged
else if (sameContents(x, getEquivalentFileInTarget(x)) && (xSourceName.equals(xTargetName))) {
System.out.println("THIS FILE AND ITS EQUIVALENT ARE EQUAL");
TreeItem newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
newBranch.setGraphic(greenDotIcon);
}
//if same name, but different contents, i.e. changed
else if ((x.getName(x.getNameCount() - 1)).equals(
getEquivalentFileInTarget(x).getName(getEquivalentFileInTarget(x).getNameCount() - 1))) {
TreeItem newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
newBranch.setGraphic(yellowDotIcon);
} else {
System.out.println("BAD, putInTreeView() Error, it should never reach this line");
System.out.println("Error log: " + x + ", " + getEquivalentFileInTarget(x));
}
} else if (x.toFile().isDirectory()){ //if it's a folder, checked explicitly because it's behaving weird
System.out.println("THIS IS A DIRECTORY: " + x.toString());
if (getEquivalentFileInTarget(x).toFile().exists()) {
System.out.println("EQUIVALENT EXISTS FOR THIS DIRECTORY IN TARGET.");
//make new branches and mark them as existing folders
TreeItem currentSourceTreeViewRoot = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
currentSourceTreeViewRoot.setExpanded(true);
currentSourceTreeViewRoot.setGraphic(greenDotIcon);
for (File i : x.toFile().listFiles()) {
System.out.println("Rec. called for: " + currentSourceTreeViewRoot);
compareAndFillInSourceTreeView(i.toPath(), currentSourceTreeViewRoot);
}
} else {
System.out.println("EQUIVALENT DOESN'T EXIST FOR THIS DIRECTORY IN TARGET.");
//if they don't exist, make the branches anyway and mark them as representing nonexistent folders
TreeItem currentSourceTreeViewRoot = makeBranch((x.getName(x.getNameCount() - 1)).toString(), root);
currentSourceTreeViewRoot.setExpanded(true);
for (File i : x.toFile().listFiles()) {
System.out.println("Rec. called for: " + currentSourceTreeViewRoot);
compareAndFillInSourceTreeView(i.toPath(), currentSourceTreeViewRoot);
}
}
}
}
Your assumption is correct. When assigning a graphic with setGraphic you are telling JavaFX where in the scene graph to locate this node. When you call setGraphic again with the same object as parameter you are effectively moving it to a different place in the scene graph.
Create a new dot/circle for every item and your problem should be solved.

Tooltip: how to get mouse coordinates that triggered the tip?

The requirement: show the coordinates of the mouseEvent that triggered the tooltip as its text. For a contextMenu, the location is stored in the contextMenuEvent, so I would listen to contextMenuRequested and update as needed.
Couldn't find anything similar for a tooltip, so played a bit (see example below):
at the time of showing/shown, I could query the tooltip location: for AnchorLocation.CONTENT_TOP_LEFT its x/y seems to be about the last mouse location, though slightly increased. Could be accidental, though, is unspecified (and as such unusable) and definitely off for other anchor types
the brute force method would be to install a mouse-moved handler and store the current mouse location into the tooltip's properties. Wouldn't like to, because that's duplicating functionality, as ToolTipBehaviour already keeps track of the triggering location, unfortunately top secretly, as usual
extending tooltip wouldn't help as well, due to the private scope of the behaviour
Any ideas?
public class DynamicTooltipMouseLocation extends Application {
protected Button createButton(AnchorLocation location) {
Tooltip t = new Tooltip("");
String text = location != null ? location.toString()
: t.getAnchorLocation().toString() + " (default)";
if (location != null) {
t.setAnchorLocation(location);
}
t.setOnShown(e -> {
// here we get a stable tooltip
t.textProperty().set("x/y: " + t.getX() + "/" + t.getY() + "\n" +
"ax/y: " + t.getAnchorX() + "/" + t.getAnchorY());
});
Button button = new Button(text);
button.setTooltip(t);
button.setOnContextMenuRequested(e -> {
LOG.info("context: " + text + "\n " +
"scene/screen/source " + e.getSceneX() + " / " + e.getScreenX() + " / " + e.getX());
});
button.setOnMouseMoved(e -> {
LOG.info("moved: " + text + "\n " +
"scene/screen/source " + e.getSceneX() + " / " + e.getScreenX() + " / " + e.getX());
});
return button;
}
#Override
public void start(Stage stage) throws Exception {
VBox pane = new VBox(createButton(AnchorLocation.CONTENT_TOP_LEFT));
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(DynamicTooltipMouseLocation.class.getName());
}
I'm not sure if I've understood your question right, but if you are looking for the screen coordinates of the mouse, right at the position when the tooltip is shown, I think you almost got them.
You have already looked at Tooltip class and its inner class TooltipBehavior.
For starters there are these hardcoded offsets:
private static int TOOLTIP_XOFFSET = 10;
private static int TOOLTIP_YOFFSET = 7;
Then, in the inner class a mouse moved handler is added to the node, tracking the mouse in screen coordinates, and showing the tooltip based on several timers:
t.show(owner, event.getScreenX()+TOOLTIP_XOFFSET,
event.getScreenY()+TOOLTIP_YOFFSET);
Given that it uses this show method:
public void show(Window ownerWindow, double anchorX, double anchorY)
The coordinates you are looking for are just these:
coordMouseX=t.getAnchorX()-TOOLTIP_XOFFSET;
coordMouseY=t.getAnchorY()-TOOLTIP_YOFFSET;
no matter how the tooltip anchor location is set.
I've checked this also in your answer to the question, and these values are the same as the Point2D screen you set to the tooltip.
Anyway, since this solution uses hardcoded fields from private API, I assume you won't like it, since those can change without notice...

Using ACE with WT

UPDATE 3
Final working code below. YOU NEED THE ace.js FROM THE src FOLDER! It will not work from the libs, you need the pre-packaged version from their site.
WText *editor = new WText(root());
editor->setText("function(){\n hello.abc();\n}\n");
editor->setInline(false);
The above code can set the contents of the ACE window.
MyClass::MyClass(const WEnvironment& env)
: WApplication(env)
{
wApp->require("ace-builds/src/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
editor->resize(500, 500);
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + ".editor = ace.edit(" + editor_ref + ");" +
editor_ref + ".editor.setTheme(\"ace/theme/monokai\");" +
editor_ref + ".editor.getSession().setMode(\"ace/mode/javascript\");";
editor->doJavaScript(command);
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
command = "function(object, event) {" +
jsignal->createCall(editor_ref + ".editor.getValue()") +
";}";
b->clicked().connect(command);
}
void MyClass::textChanged(std::string incoming)
{
}
UPDATE 2
Here is what my project looks like atm, still getting a white screen with a red "Loading..." message from WT in the top right hand corner. More notes below.
MyClass::MyClass(const WEnvironment& env)
: WApplication(env)
{
wApp->require("lib/ace/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
editor->resize(500, 500);
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + ".editor = ace.edit(" + editor_ref + ");" +
editor_ref + ".editor.setTheme(\"ace/theme/monokai\");" +
editor_ref + ".editor.getSession().setMode(\"ace/mode/javascript\");";
editor->doJavaScript(command);
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
command = "function(object, event) {" +
jsignal->createCall(editor_ref + ".editor.getValue()") +
";}";
b->clicked().connect(command);
}
void MyClass::textChanged(std::string incoming)
{
}
"command" variable is equal to the following when it is used for editor->doJavaScript(command)
"Wt3_3_0.$('oy4ycjy').editor = ace.edit(Wt3_3_0.$('oy4ycjy'));Wt3_3_0.$('oy4ycjy').editor.setTheme('ace/theme/monokai');Wt3_3_0.$('oy4ycjy').editor.getSession().setMode('ace/mode/javascript');"
"command" variable is equal to the following when it is used for b->clicked().connect(command);
"function(object, event) {Wt.emit('oy4ycjy','textChanged',Wt3_3_0.$('oy4ycjy').editor.getValue());;}"
UPDATE 1
Added the suggested code to my constructor, however the page does not change from a solid white screen. I am doing nothing else in this WT project, only this code is running.
wApp->require("lib/ace/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
editor->doJavaScript(
editor_ref + ".editor = ace.edit('" + editor_ref + "');" +
editor_ref + ".editor.setTheme('ace/theme/monokai');" +
editor_ref + ".editor.getSession().setMode('ace/mode/javascript');"
);
The value of editor_ref is "Wt3_3_0.$('oumvrgm')" minus the quotes.
Also tried adding the code below, and the page is still blanked out.
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
b->clicked().connect("function(object, event) {" +
jsignal->createCall(editor->jsRef() + ".editor.getValue()") +
";}");
I have also found that commenting out
editor_ref + ".editor = ace.edit('" + editor_ref + "');" +
makes the button show up, but there is a red "Loading..." note at the top right of the screen so WT is waiting on something.
I have textChanged as a do nothing function at the moment.
ORIGINAL POST
So, my problem is this. How can I get ACE http://ace.ajax.org/#nav=about in WT http://www.webtoolkit.eu/wt. More specifically, ACE in a WT Wt::WTextArea or Wt::WTabWidget, the text area would be preferred. I have been trying to do this for a few days now and have not had much success.
I've been able to embed ACE in an HTML page no problem, as their site says "just copy and paste it into your page" and it really is that simple. However, I need to load it locally through WT and into a container. I downloaded their repos from GIT to my machine and have tried using
require("lib/ace/ace.js");
and
doJavaScript(...);
with various commands to no success... I am not nearly as strong in Java and HTML as C++ so I will ask for as much detail as possible if this involves a lot of Java/HTML. Thanks in advance mates!
Maybe this puts you in the right direction:
wApp->require("lib/ace/ace.js")
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(parent);
// editor->jsRef() is a text string that will be the element when executed in JS
editor->doJavaScript(
editor->jsRef() + ".editor = ace.edit(" + editor->jsRef() + ");" +
editor->jsRef() + ".editor.setTheme('ace/theme/monokai');" +
editor->jsRef() + ".editor.getSession().setMode('ace/mode/javascript');"
);
That should decorate the editor. Wt does not automatically send the modifications to a div to the server, so you do this manually through a JSignal (emits a signal from JS to C++):
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, MyClass::textChanged);
WPushButton *b = new WPushButton("Save", parent);
b->clicked().connect("function(object, event) {" +
jsignal->createCall(editor->jsRef() + ".editor.getValue()") +
";}");
(code above is not tested so you may need to adjust a bit)
I have integrated CodeMirror in an earlier JWt (java) project like this:
import eu.webtoolkit.jwt.WApplication;
import eu.webtoolkit.jwt.WContainerWidget;
import eu.webtoolkit.jwt.WTextArea;
public class CodeMirrorTextArea extends WContainerWidget {
private WTextArea textArea;
public CodeMirrorTextArea(WContainerWidget parent) {
super(parent);
textArea = new WTextArea(this);
WApplication app = WApplication.getInstance();
app.require(app.resolveRelativeUrl("codemirror-2.32/lib/codemirror.js"));
app.require(app.resolveRelativeUrl("codemirror-2.32/mode/groovy/groovy.js"));
//TODO:
//We save the editor state to the text area on each key stroke,
//it appears to be not a performance issue,
//however it might very well become one when editing larger fragments of code.
//A better solution would be to save this state to the text area only when
//the form is submitted, currently this is not yet possible in Wt???.
String js =
"var e = " + textArea.getJsRef() + ";" +
"var cm = CodeMirror.fromTextArea(e, {" +
" onKeyEvent : function (editor, event) {" +
" editor.save();" +
" }," +
" lineNumbers: true" +
" });" +
"var self = " + getJsRef() + ";" +
"self.cm = cm;";
this.doJavaScript(js);
}
public CodeMirrorTextArea() {
this(null);
}
public void setText(String text) {
textArea.setText(text);
}
public String getText() {
return textArea.getText();
}
public void setMarker(int line, String htmlMarker) {
String js =
"var self = " + getJsRef() + ";" +
"self.cm.setMarker(" + line + ", " + jsStringLiteral(htmlMarker +
"%N%") + ");";
this.doJavaScript(js);
}
public void clearMarker(int line) {
String js =
"var self = " + getJsRef() + ";" +
"self.cm.clearMarker(" + line + ");";
this.doJavaScript(js);
}
}

Categories