I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:
public static void main(String[] args) {
Game game = new Game();
// This right here!
game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());
game.frame.setResizable(false);
game.frame.setTitle(title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
}
My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:
IconImageUtilities.setIconImage(this);
The below method works well on Java 7 and above.
JFrame frame = new JFrame("MyAPP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
frame.setIconImage(ImageIO.read(YourClass.class.getResourceAsStream("/icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
frame.setVisible(true);
Park your icon.png image file to /src/main/resources.
Related
Hello Everyone i'm trying to use vlcj for java but am running into a lot of errors. I checked my jvm version and vlc media version both are 64 bit.
I tried a lot of codes that I had researched in the internet. I followed the step by inserting vlcj.jar in my code but nothing seems to work.
I followed the tutorial on caprica but it wouldn't work. Now i'm getting error
Exception in thread "main" java.lang.IllegalArgumentException: Interface (LibVlc) of library=libvlc does not extend Library B.
Can someone please help on this?
package mrbool.vlc.example;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.binding.LibVlc;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.RuntimeUtil;
public class JavaApplication1 {
public static void main(String[] args) {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),"C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
MediaPlayerFactory factory = new MediaPlayerFactory();
}
}
install vlc media player in to same directory that your project is located
Sometimes the problem is due to incompatibility of the architecture of VLC and JRE.
You can check JRE architecture using the code below:
public class JavaApplication12 {
public static void main(String[] args) {
System.out.println(System.getProperty("sun.arch.data.model"));
}
}
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
EmbeddedMediaPlayer embeddedMediaPlayer = mediaPlayerComponent.getMediaPlayer();
Canvas videoSurface = new Canvas();
videoSurface.setBackground(Color.black);
videoSurface.setSize(800, 600);
List<String> vlcArgs = new ArrayList<String>();
vlcArgs.add("--no-plugins-cache");
vlcArgs.add("--no-video-title-show");
vlcArgs.add("--no-snapshot-preview");
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(vlcArgs.toArray(new String[vlcArgs.size()]));
mediaPlayerFactory.setUserAgent("vlcj test player");
embeddedMediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(videoSurface));
embeddedMediaPlayer.setPlaySubItems(true);
final PlayerControlsPanel controlsPanel = new PlayerControlsPanel(embeddedMediaPlayer);
PlayerVideoAdjustPanel videoAdjustPanel = new PlayerVideoAdjustPanel(embeddedMediaPlayer);
// mediaPlayerComponent.getMediaPlayer().playMedia(Constant.PATH_ROOT + Constant.PATH_MEDIA + "tmp.mp4");
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.setBackground(Color.black);
mainFrame.add(videoSurface, BorderLayout.CENTER);
mainFrame.add(controlsPanel, BorderLayout.SOUTH);
mainFrame.add(videoAdjustPanel, BorderLayout.EAST);
//create a button which will hide the panel when clicked.
mainFrame.pack();
mainFrame.setVisible(true);
embeddedMediaPlayer.playMedia("tmp.mp4");
Also, to do this yourself I would suggest using chrome. You just right click on whatever you want to scrape and go to inspect element. It will take you to the exact spot in the html where that element is located. In this case you first want to find out where the root of all the result listings are. When you find that, you want to specify the element, and preferably an unique attribute to search it by. In this case the root element i
public class ScanWebSO
{
public static void main (String args[])
{
Document doc;
try{
doc = Jsoup.connect("https://www.google.com/search?as_q=&as_epq=%22Yorkshire+Capital%22+&as_oq=fraud+OR+allegations+OR+scam&as_eq=&as_nlo=&as_nhi=&lr=lang_en&cr=countryCA&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=").userAgent("Mozilla").ignoreHttpErrors(true).timeout(0).get();
Elements links = doc.select("li[class=g]");
for (Element link : links) {
Elements titles = link.select("h3[class=r]");
String title = titles.text();
Elements bodies = link.select("span[class=st]");
String body = bodies.text();
System.out.println("Title: "+title);
System.out.println("Body: "+body+"\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I want to include a font as a resource file in my deployed application.
To use it in swing, I know that I can import a font like this:
InputStream is_regular = Resources.class.getResourceAsStream("Lato-Regular.ttf");
Font regular_font = Font.createFont(Font.TRUETYPE_FONT, is_regular);
But how can I register also the bold variant, which is stored in a file called "Lato-Bold.ttf"?
I also know that I can access the variant weights via the attributes field. But how do I register these?
The Lato Font comes in 18 different variants such as light, semibold, hairline, etc.
You write a FontManager. The solution to almost any Java problem is either a manager or a factory. Sometimes you need a manager-factory.
One way would be like this.
package com.ggl.testing;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resources;
public class FontManager {
public static Font getNormalFont() {
return getFont("Lato-Regular.ttf");
}
public static Font getBoldFont() {
return getFont("Lato-Bold.ttf");
}
private static Font getFont(String fontFileName) {
InputStream is = Resources.class.getResourceAsStream(fontFileName);
try {
return Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
You write a getter method for the 18 variations of your font.
The return null at the end of the getFont method can be changed to return a standard font.
If you want to deploy the fonts with your application, you need to copy the font files into a resource folder in your application. You add the application resource folder to your Java build path (classpath). This line in the code would change to
InputStream is = getClass().getResourceAsStream("/" + fontFileName);
I am try to open a javadoc html file with my new application, however I can not get the javadoc file to open, I have a class name OpenUri, which when called is supposed to open the javadoc:
package gui;
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JFrame;
public class OpenUri extends JFrame {
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
I am then calling and using this class from another class called Menu, where the help button has an action listener, etc. However when I run the code and press the help button, no javadoc appears, ie, it doesn't open the document, ie, nothing happens, no window, nothing ?
The only way I can open it is manually, by clicking on it in eclipse, here is the specific code from the Menu class I am Using:
//Help
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
try {
URI uri = new URI("file:///C:/Users/howhowhows/workspace/OPTICS_DROP_MENU/doc/index.html");
OpenUri.openWebpage(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
});
If anyone has any ideas as to what I am doing wrong, ie what I need to add/change, it would be greatly appreciated.
Have you downloaded and tried the demo code from the Swing tutorial on How to Integrate With the Desktop Class.
When I used that code and pasted your URI into the text field no window is displayed and I get a "System cannot find the file" message as expected.
When I then enter a simple URI that I know exists: "c:/java/a.html" the browser opens as expected.
So I suggest you start with known working code and see if your URI works. If it does work then the problem is your code, so compare the working code to your code to see what the difference is. If it doesn't work then the problem is the URI.
If you still have problems then post a proper SSCCE that demonstrates the problem. Given that your OPenURI class extends JFrame for no reason we don't know what other strange things you might be doing in your code.
I've started Java a week ago, and now I would like to insert an image into my window.
Whatever I try I keep having this in Eclipse:
javax.imageio.IIOException: Can't read input file!
package graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import src.Common;
public class Window extends JFrame
{
public class Panel extends JPanel
{
public void paintComponent(Graphics g)
{
Image img;
try
{
img = ImageIO.read(new File("/logo.jpg"));
g.drawImage(img, 0, 0, this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public Window(String title, int width, int height)
{
this.setTitle(title);
this.setSize(width, height);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new Panel());
this.setVisible(true);
}
}
I think the code is pretty self-explaining.
I tried to solve the problem with this, this, and that .
What I'm trying to do is a desktop program, and my sources are stored like that :
training/src/graphics/Window
training/src/src/main
I did put the image I want to read in every folder, and still getting the issue :/
What did I do wrong?
EDIT Finally solved, here the answer
nIcE cOw gave me the link that helped.
So I did put my images into a folder, and change the way to access to them, as described in the link.
getClass().getResource("/images/yourImageName.extension");
Have you tried using new File("logo.jpg"); (without the leading /)?
And are you sure, the logo.jpg is copied to your output? (Some IDEs don't copy every file from your source-directories to your output (or target) directories.)
/src
|-> Window.java
|-> Logo.jpg
becomes
/out
|-> Window.class
(Note that the IDE/compiler does not copy the image to your output-directory and so the compiled code cannot find the image - allthough you did specify the correct path)
Try do debug which file resource you actually try to access. First step would be to get your new File("/logo.jpg").get [Canonical]Path() and print it to System.out (or alternatively watch in the the debugger). I guess the problem is the / before logo.jpg, which points to your root directory (e.g. c:) and your file isn't there, but I don't know your file setup in detail.
The problem is that you're looking at nothing before the image, so it's looking into a folder that isn't there to find it.
You have to create a folder to store the images in your project, and then call to it, your folder name in front of the image name. e.g.
ImageIO.read(new File("Folder/Image.png"));
Otherwise you can find the image by going through the entire directory, which isn't a good way as it takes longer, and when you move your project it won't be a working link as the directory will be different. For example:
ImageIO.read(new File("D:/eclipse/Workspace/Project/Folder/Image.png"));
Creating a folder in your project so its on the same level as the source folder in the directory and call to it for the image, like so:
Folder structure;
settings
src
Image Folder
bin
copypasting from a working project:
private JPanel getPanel() {
JPanel panel = new JPanel();
JLabel labelLcl = new JLabel("Ye ana!");
try {
File f = new File("./src/res/0.jpg");
//l.a(f.getCanonicalPath());
BufferedImage imgLcl = ImageIO.read(f);
ImageIcon iconLcl = new ImageIcon(imgLcl);
labelLcl.setIcon(iconLcl );
panel.add(labelLcl);
} catch (IOException e) {
e.printStackTrace();
}
return panel;
}
otherwise you can have folder/file read permission problem
I'm trying to create a splash screen using LWUIT. I want a form to load and display text and an imagefor 5 seconds then continue to the next form. I have a code but fails to show the image. The class and the image are stored together int he same package. Instead, it shows an error.
java.io.IOException
What could be the problem? This is the code
package tungPackage;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import javax.microedition.midlet.MIDlet;
public class photoMidlet extends MIDlet {
public void startApp() {
Display.init(this);
try {
Form splashscreen = new Form();
// Label splashText = new Label("Baldy");
Image image = Image.createImage("/splash.png");
Label pictureLabel = new Label(image);
splashscreen.addComponent(pictureLabel);
splashscreen.show();
} catch (Exception ex) {
Form x = new Form("ERROR");
String y = ex.toString();
Label g = new Label(y);
x.addComponent(g);
x.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Open your JAR file using a ZIP utility (e.g. 7-zip) and look in the root of the file. If splash.png isn't in the root of the jar that's your problem!
Place splash.png so it is in the root of the jar.