I'm currently trying to make a custom button using JavaFX. I have defined 2 styles that contain 2 different images for 2 button states(Pressed and Free). I'm using Intellij Idea and when defining the paths it shows no error's, but the button doesn't show up. Its just transparent, but I can click it. I have tried specified different paths, but haven't gotten any result. Here is the code where I define the styles and my file tree. Thanks!
public class CustomButton extends Button {
private final String FONT_PATH = "src/Resources/GUI/pixelFont.ttf";
private final String BUTTON_PRESSED_STYLE = "-fx-background-color: transparent;" +
" -fx-background-image: url('../../Resources/GUI/Buttondown.png');";
private final String BUTTON_FREE_STYLE = "-fx-background-color: transparent;" +
" -fx-background-image: url('../../Resources/GUI/Buttonup.png');";
public CustomButton(String text) {
setFont();
setPrefWidth(180);
setPrefHeight(53);
setText(text);
setStyle(BUTTON_PRESSED_STYLE);
initButtonListeners();
}
}
File tree
Moving all of the files into the pre-generated by Intellij Idea resources folder and then using that folder solved the issue.
Related
I wish to use one of my local sound files to provide background music, but I get this error message:
Caused by: java.lang.UnsatisfiedLinkError: Can't load library: C:\Program Files\Amazon Corretto\jdk1.8.0_232\jre\bin\glib-lite.dll
But my code is as follow:
public class DungeonGUI extends Application {
private Dungeon dungeon;
private Stage stage;
private GridPane root;
private Button attack;
private Button heal;
// private Button checkInventory;
private Button save;
private Text characterHealth;
private Text characterPower;
private Text characterInventory;
private Text monsterHealth;
private Text monsterPower;
private File audioFile = new File("C:/Users/15774/Downloads/oof.mp3");
#Override
public void start(Stage stage) throws Exception {
setButtons();
dungeon = new Dungeon();
setTexts();
this.stage = stage;
root = new GridPane();
heal.setOnAction(this::onHeal);
attack.setOnAction(this::onAttack);
save.setOnAction(this::onSave);
stage.setTitle("Dungeone Dungeon");
root.setAlignment(Pos.CENTER);
setMedia();
setupRoot();
setStage(stage);
}
private void setMedia() {
Media media = new Media(audioFile.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
}
As you can see I did not call program files at any time. What might be the problem?
P.S.: this is only part of my code. If you guys need more information just shoot a comment.
Amazon Corretto for Java 8 does not support JavaFX. See here for full insight. However, as short, I refer to the following quote from the page:
The recommended way of using JavaFX is with Corretto 11 and pulling in OpenJFX separately e.g. with a Maven dependency. The latest version (currently 14) is compatible with Corretto 11.
src: Corretto's github
jccampanero also here answered a similar question.
I'm using the following to show a cross in a label, that accompanies an if statement.
JLabel.setIcon(new ImageIcon(path + "Resource/cross.png"));
Instead of loading the icon everytime I would prefer to have it imported into my project and call it from there. I know how to import it but how do I modify the line of code above to point to the imported icon.
you can create a static loader methode (in an utility class) and store it there
private static Map<String, Icon> lookUpMap = new HashMap<>();
public static Icon getImageIcon(String res){
Icon icon = lookUpMap.get(res);
if(icon = null){
icon = new ImageIcon(res);
lookUpMap.put(res, icon);
}
return icon;
}
you can access the icons now everywhere
JLabel.setIcon(UtilitClass.getImageIcon(path + "Resource/cross.png));
I'm using eclipse to created an RCP Application, and I'm not being able to load an image because I don't know how to find it in the generated code. I'm going to try to explain my particular issue.
Note: the project is a Game editor, and it is located here: http://chelder86.github.com/ArcadeTongame/
Firstly, this is the project structure:
The next code runs the RCP application correctly inside Eclipse, after changing the Working Workspace in the Eclipse Running Config.
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = "src/figures/Sound48.png";
// or String picturePath = "bin/figures/Sound48.png";
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
But it does not work when I create a Product and export it as an RCP Application. I mean, the RCP application works, but it does not load that image.
Note: build.properties has the image checked.
I tried different combinations like these with the same result: java.io.FileNotFoundException, when I run it in Eclipse:
package figures;
(...)
public class Sound extends ImageFigure {
public Sound() {
String picturePath = getClass().getResource("Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("bin/figures/Sound48.png").getPath();
// or String picturePath = this.getClass().getClassLoader().getResource("figures/Sound48.png").getHost();
// or similars
Image image = new Image(null, picturePath);
this.setImage(image);
}
}
How could I load it correctly?
Thanks for any help! :)
Carlos
Try creating a separate "figures" folder alongside "icons" folder. Put only the image files there, not .java files. Don't forget to add it to the class path and to build.properties. Then something like this should work:
InputStream in = getClass().getResourceAsStream("figures/Sound48.png");
Image image = new Image(Display.getDefault(), in);
I have a JEditorPane created by this way:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
I put this pane on a JFrame.
Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)
You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps:
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
Test.createAndShowGUI();
}
private static void createAndShowGUI() throws IOException {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String imgsrc =
Test.class.getClassLoader().getSystemResource("a.jpg").toString();
frame.getContentPane().add(new JEditorPane("text/html",
"<html><img src='"+imgsrc+"' width=200height=200></img>"));
frame.pack();
frame.setVisible(true);
}
}
The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory.
Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.
None of the above worked for me, however 'imgsrc = new File("passport.jpg").toURL().toExternalForm();' let me to try and have each image in the html have a preceding 'file:' so that it now reads:
<img src="file:passport.jpg" />
And that works fine for me.
If you want to specify relative path to the image.
Let's say your project folder structure is as following:
sample_project/images
sample_project/images/loading.gif
sample_project/src
sampler_project/src/package_name
Now the image tag would look like this:
"<img src='file:images/loading.gif' width='100' height='100'>"
Yaay!
I used this when I was working in netbeans, it worked though. I think a little modification if the program should run outside of netbeans,
String imgsrc="";
try {
imgsrc = new File("passport.jpg").toURL().toExternalForm();
} catch (MalformedURLException ex) {
Logger.getLogger(EntityManager.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(imgsrc); use this to check
html = "<img src='" + imgsrc + "' alt='' name='passport' width='74' height='85' /><br />";
//use the html ...
if you run from the jar, the image file has to be on the same directory level, ...
in fact, the image file has to be on the same directory as your execution entry.
I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
The class that contains this code is in the com.xyz package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.
Anyone have a solution that works?
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
Try This write after
initcomponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));
/** Creates new form Java Program1*/
public Java Program1()
Image im = null;
try {
im = ImageIO.read(getClass().getResource("/image location"));
} catch (IOException ex) {
Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
}
setIconImage(im);
This is what I used in the GUI in netbeans and it worked perfectly
In a class that extends a javax.swing.JFrame use method setIconImage.
this.setIconImage(new ImageIcon(getClass().getResource("/resource/icon.png")).getImage());
You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.
public static final URL ICON16 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug16.png");
public static final URL ICON32 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug32.png");
public static final URL ICON96 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug96.png");
List<Image> images = new ArrayList<>();
try {
images.add(ImageIO.read(HelperUi.ICON96));
images.add(ImageIO.read(HelperUi.ICON32));
images.add(ImageIO.read(HelperUi.ICON16));
} catch (IOException e) {
LOGGER.error(e, e);
}
// Define a small and large app icon
this.setIconImages(images);
You can try this one, it works just fine :
` ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
this.setIconImage(icon.getImage());`
inside frame constructor
try{
setIconImage(ImageIO.read(new File("./images/icon.png")));
}
catch (Exception ex){
//do something
}
Example:
URL imageURL = this.getClass().getClassLoader().getResource("Gui/icon/report-go-icon.png");
ImageIcon iChing = new ImageIcon("C:\\Users\\RrezartP\\Documents\\NetBeansProjects\\Inventari\\src\\Gui\\icon\\report-go-icon.png");
btnReport.setIcon(iChing);
System.out.println(imageURL);