How to loop through all fxml resources? - java

Is there a way to loop through or access all fxml files in the resources folder?
Something like:
getAllResources().size()
or
for (URL url : resources) {
...
}
instead of accessing each resource individually through the fxml loader.
I'm building a JavaFX application with multiple scenes and want to switch between them like in this example with the SceneController:
How to switch scenes in JavaFX
So in the main class, all resources get "registered" and added to the screen controller.
Looks like this in my case:
ScreenController.addScreen("scene1", FXMLLoader.load(Objects.requireNonNull(getClass().getResource("scene1.fxml"))));
ScreenController.addScreen("scene2", FXMLLoader.load(Objects.requireNonNull(getClass().getResource("scene2.fxml"))));
...
As we can see, it's always the same line, which is ugly and a clear sign for using a loop.

Related

Play: How to prevent 404 on image src on first request after upload

I've got a simple form with 2 text and 1 file input
#helper.form(action = routes.CharactersController.newCharacter(), 'enctype -> "multipart/form-data") {
#helper.inputText(field = characterForm("characterName"))
#helper.inputText(field = characterForm("characterRealName"))
#helper.inputFile(field = characterForm("characterImage"))
<p>
<input type="submit">
</p>
}
in the newCharacter action I move the file to the asset folder.
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> picture = body.getFile("characterImage");
File file = picture.getFile();
file.renameTo(new File(LinkUtil.getCharacterUploadPath(), imageName + ".jpg"));
and then make a redirect to the /show page to display the new entered character
return redirect(routes.CharactersController.show(character.id, OrderType.MAIN.name()));
On the newly loaded page I only get a broken image and see a 404 in the console for the image. When I reload the page the image is rendered as expected.
So which part isn't ready when I redirect? Is it the renameTo or does play need some time to find the new asset?
And how can I ensure everything is ready before I redirect?
Edit:
To improve my question
I'm using play 2.5
LinkUtil.getCharacterUploadPath() resolves to "public/images/characters/"
I'm embedding the image in my show template like this:
<img src="#character.getImagePath">
which then resolves to "/assets/images/characters/imagename.jpg"
Edit 2: Further investigations:
When I check the filesystem within the newCharacter action with something like file.exists() for the new path, I get true. So the rename/moving part seems finished.
However if I try to get the resource via environment
environment.getResource("relativePathToFile");
it's null. Even within a while loop the resource stays null. Which seems to indicate that the file isn't really added to the classpath yet. Unfortunately no matter how long I stay in the action the resource is always null. But when I put the Thread to sleep for 2000ms and then check the resource again in the show action it gets resolved properly. But only if I wait for 2s.
Another test was to utilize a onerror="window.location.reload()" on the image. Which results in about 5-10 reloads before the image is found.
So it's definetely a matter of time, but putting the Thread to sleep for an arbitrary amount feels plain wrong.
There has to be a way to be sure that the file is available on the classpath.
Every hint/idea is appreciated.
I got it to work! First my approach above was flawed.
Taking uploaded images, putting them into the public folder and trying to serve them with the AssetController won't work on a production build. Everything in the public folder is packaged into a .jar file. And some quick test hinted that my renameTo from above won't put the images where I expected them to be.
So here my solution:
Define a new route:
GET /files/*file controllers.Images.serve(file)
In the action use an absolute path on the filesystem
public class Images extends Controller {
public Result serve(String file) {
return ok(new java.io.File("/var/www/files/" + file));
}
}
Access the file with something like this
<img src="/files/images/characters/imagename.jpg">
The Image is accessible instantly on the redirect request.
My guess about the delay in the Question is, that play tries to compile everything that is added to the classpath before making it accessible

How to use GWTQuery-UI

I am trying to unserstand how GWTQuery works, for that I am trying out a simple demo with the slider. As per the documentation at Google (the slider tab is on the bottom left), and using the class AbstractSliderDemo from here, which in turn, is implementing the Demo interface defined here, my onModuleLoad simply contains:
Label e = $("#slider").widget();
Query q = new Query();
q.setupDemoElement(e.getElement());
However on page-load, it is throwing a NullPointer exception. Can anybody guide me how to use it. Probably I am missing something here. (I have added both GWTQuery and GWTQuery-UI jar files to the build path, as well as including <inherits name='gwtquery.plugins.Ui' /> in the XML file).
And here is the directory structure of my project:
GwtQuery-Ui is just a wrapper on jquery-ui. That means that you need to inject the jquery and jquery-ui javascript file. Check the getting started guide og GwtQuery-ui

Error with Images

I recently finished the basics of a game that I'm making and I was going to send it to some friends, but whenever they open the .jar it's just a grey window. When I heard that I assumed it was because of the way I got the images (I used a full path: C:\Users\etc). I did some Googling and found a way to get images that seemed more efficient.
private static Image[] mobImages = new Image[1];
public static void loadImages()
{
mobImages[1] = Handler.loadImage("res/EnemyLv1.png");
}
public static Image getMobImages(int index)
{
return mobImages[index];
}
That's what I would like to use. But I did that and changed the rest of my code to support that. And whenever I run a game I get a few errors. Which all point back to
this:
if(getBounds().intersects(tempEnemy.getBounds()))
and so probably the way I'm getting the images too. How could I fix this? And are there better ways to get Images? I've tried a few but they haven't worked.
EDIT: I finally solved all of the errors! :D The only problem is that none of the images appear. Here's my code again. Any more help? That would be fantastic! Thanks everybody for the support so far!
Hard to say whats going wrong in your code. However I recommend you put your image files into a package in the java project (so they will be part of the JAR file) and access them using Class.getResource()/Class.getResourceAsStream(). That avoids multiple pitfalls and keeps everything together.
A sample how to structure your images into the packages:
myproject
images
ImageLocator.class
MyImage1.jpg
MyImage2.jpg
The ImageLocator class then needs to use relative pathes (just the image name + extension) to access to resources.
public class ImageLocator {
public final static String IMAGE_NAME1 = "MyImage1.jpg";
public static Image getImage(final String name) {
URL url = ImageLocator.class.getResource(name);
Image image = Toolkit.getDefaultToolkit().createImage(url);
// ensure the image is loaded
return new ImageIcon(image).getImage();
}
}
This can be done more elegant, but this should get you started. Defining the image names as constants in the ImageLocator class avoids spreading the concrete path throughout the project (as long as the name is correct in ImageLocator, everything else will be checked by the compiler)
Your code still uses "C:\Users\Kids\Desktop\Java Game\Cosmic Defense\res\EnemyLv2.png" in Enemy.java. Are you sure this exists? If you moved the Cosmic Defense folder, it will not.
(You were talking about changing absolute paths to relative paths, so this may be your problem)
Part of the reason could be that your code is pointing to an index of "1" in an array of size 1, meaning that the only available index is in fact "0".
Try mobImages[0] = Handler.loadImage("res/EnemyLv1.png");

want to access the css styles from my java code

i have a css in my GWTApplication which contains several classes in that,I want to access the class attributes through my program,is there any way to access them via java code or CssResource.
If there is any let me know with the sample code?
One can access CSS classes through GWT code but not its class attributes through setStyleName(String) method. For example
Button button = new Button();
button.setStyleName("Stylename");
for example css of
.StyleName {
background : #abcdef;
}
Further you can change the value of some attributes without css like
button.setWidth("100px");
button.setHeight("20px");
Take a look at SAC : http://www.w3.org/Style/CSS/SAC/Overview.en.html

GWT inter project communication

We have a large GWT project and many smaller GWT sub-projects
basically the large controller project invokes the smaller projects
via many means such as some are incorporated into iframes that are shown in page,
some are shown by clicking a URL and opening the project into a new window.
The requirement is to change the Css on the fly, this is possible in the main project,
by simply changing, on the fly, the href of the link tag containing stylesheet url
is it possible to propogate this change to the sub-projects too ?
or asking in more broader terms,
how do i achieve inter - project communication in GWT ?
A browse allows you to call Javascript code across IFrames if the domains of the different GWT applications are the same.
Using JSNI you can register methods on the window object which call back into the GWT application and using JSNI the other project can invoke this method.
If all the apps are served from the same domain you could store the name of the stylesheet in a cookie. Each app would then use the cookie to select the appropriate stylesheet.
String theme = Cookies.getCookie("THEME");
if (theme == null) {
theme = "default";
}
Element e = DOM.createElement("link");
DOM.setElementProperty(e, "rel", "stylesheet");
DOM.setElementProperty(e, "href", GWT.getModuleBaseURL() + currentTheme +
".css");
DOM.appendChild(getHead(), e);
private native Element getHead() /*-{
return $doc.getElementsByTagName('head')[0];
}-*/;

Categories