So i am new to Java and this will probaly the easiest question you will ever see, still I can not find the anser on the internet.
I want to set the icon of my program, This code does works:
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("MYPROBLEM"));
Yet i can not get the path correct at the MYPROBLEM section. This is my structure:
Projectname
-src
--default package
---myfunctions
--test <----a map
---icon.png
Whenever i replace MYPROBLEM with src/test/icon.png it does work. however when i export my application as jar the default Java icon shows up. Replacing MYPROBLEM with something like test/icon.png does also not works.
I do appologise for my English. Bear with me because I am a newbie ;)
This will load an image from the classpath.
Image image = new ImageIcon(this.getClass().getResource("MYPROBLEM")).getImage();
frame.setIconImage(image);
for some reason sometimes it does not work but what you can do is to add the full path of the location of the image. here is an example
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class JFrameIcon {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 150);
frame.setTitle("tutorialData.com");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Sirnurpc\\Desktop\\icon.png"));
frame.setVisible(true);
}
}
reference seticon
In your case if you are using Netbeans then the location would be
C:\Users\yourloginname\Documents\NetBeansProjects\yourproject\imagename.png
And for Eclipse which I am guessing you are using would be something like this
C:\Users\yourlogingname\workspace\yourproject\imagename.png
Related
I have been trying to get the Java version of Chromium Embedded Framework (JCEF) to work on Eclipse for some time. I am able to verify that the library files are working correctly, since if I run the included sample class files on the VM, the program runs and some webpage is displayed. However, if I run the program from Eclipse, the program will always display a blank window. I am able to verify that the library binary jcef_helper.exe is successfully run, but not matter how I link the .jar files and other library files, the webpage will not generate and there will always be a blank screen. I cannot pinpoint the issue here. I tried specifying path, adding the JCEF library path of my OS environment variables PATH field to no avail. I have followed the documentation, even sample files behave the same way when I have anything to do with compilation/ run. One note of interest, my Eclipse console will display this during run:
initialize on Thread[AWT-EventQueue-0,6,main]
Perhaps there is a thread issue?
Code in question:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import org.cef.CefApp;
import org.cef.CefApp.CefAppState;
import org.cef.CefClient;
import org.cef.CefSettings;
import org.cef.browser.CefBrowser;
import org.cef.handler.CefAppHandlerAdapter;
public class WebV
{
public static void main(String args[])
{
Dimension dispDimension = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int)Math.round(dispDimension.getWidth() / 2);
int height = (int)Math.round(dispDimension.getHeight() / 2);
CefApp.addAppHandler(new CefAppHandlerAdapter(null)
{
#Override
public void stateHasChanged(CefAppState state)
{
if(state == CefAppState.TERMINATED)
{
System.exit(0);
}
}
});
CefSettings settings = new CefSettings();
settings.windowless_rendering_enabled = false;
CefApp cefApp = CefApp.getInstance(settings);
CefClient client = cefApp.createClient();
CefBrowser browser = client.createBrowser("http://www.google.com", false, false);
Component browserComponent = browser.getUIComponent();
JFrame frame = new JFrame();
frame.setTitle("WebV");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.add(browserComponent);
frame.setVisible(true);
}
}
Tested with both Java 17 and Java 8.
Run on Eclipse, with VM args:
-Djava.library.path=./bin/lib/win64
Any inupt would be greatly appreicated.
This answer was kindly provided by 'Yanovsky' at the JCEF forums.
The simple example provided by the JCEF package is incomplete.
We need to add a CefMessageRouter instance to our browser client. This is demonstrated in the detailed examples, but not the simple one. This code should be added before we create our CefBrowser instance and after we have created a CefClient object:
CefMessageRouter msgRouter = CefMessageRouter.create();
msgRouter.addHandler(new MessageRouterHandler(), true);
msgRouter.addHandler(new MessageRouterHandlerEx(client), false);
client.addMessageRouter(msgRouter);
For reference, this is my post in the JCEF forum:
https://magpcss.org/ceforum/viewtopic.php?f=17&t=18834&sid=45381db639d1621f2f8b38b4d8848800
I just copied and pasted your code in eclipse and added the jars and ran the code and voila, google.com opened without any issues.
I didnt have to add any more new lines as suggested by mindoverflow.
The webpage was visible in the window after a few secs and not immediately.
Here's what popped up after running the code.
And in the eclipse console, I see this
initialize on Thread[AWT-EventQueue-0,6,main] with library path C:\path\to\dlls
I'm following along with this tutorial, and I got a problem early in the video (at approximately 7:45). I'm trying to create a basic Java program that will launch a window, however, I can't seem to import JFrame.
I've looked for other solutions on Stack Overflow, but I haven't found one that works for me.
Here is the code I've written:
import javax.swing.JFrame;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World");
frame.setVisible(true);
}
}
I'm using Eclipse version 4.12.0 on a Macbook Pro (13-inch, Mid 2012) running macOS Mojave version 10.14.5
Expected result: A window opens when I run the program, and when I close the window, the program ends.
Actual result: No window is created and I get this error message:
Error occurred during initialization of boot layer
java.lang.module.FindException: Error reading module: /Users/username/eclipse-workspace/Swing1/bin
Caused by: java.lang.module.InvalidModuleDescriptorException: App.class found in top-level directory (unnamed package not allowed in module)
If you have a module-info.java file, put this in the module:
requires java.desktop;
If you have created the java app with eclipse your fault is the package.
With eclipse, I created a java app and this is the result
This code fixed your foult
package demo;
import java.awt.Dimension;
import javax.swing.JFrame;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World");
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(400, 400));
frame.setVisible(true);
}
}
The reference for understand the package
I had the same issue. I did similar code in Eclipse. I got the error The type javax.swing.JFrame is not accessible on the side of import javax.swing.JFrame;
The solution is:
Delete the line of import javax.swing.JFrame;
And then, inside your body of your code inside your main, with your mouse, hover over JFrame keyword, and Eclipse will offer some auto-completion suggestion.
Select import 'JFrame' (javax.swing)
This will bring the required import automatically. It is a kind of shortcut.
In order to avoid these type of errors: Never type manually, get the imports AND methods, for example setVisible by autofilling. For instance, type frame.setV and again Eclipse will suggest the completion ... select from there. I do not know why, but this is what happened in my case.
The code below works fine in Eclipse (both image-handling possibilities). But when exporting as a Runnable JAR File, and double-clicking the .JAR, nothing happens. If I comment out the image parts of the code, the .JAR runs fine as an export and the frame builds. So it seems the getting of the image is causing the .JAR to fail.
I've got the strawberry.jpg file sitting in 'C:\Users\sean\workspace\myApps\bin\testing' Could you advise if the issue is with my code?
(Code first modified here: Java Swing: unable to load image using getResource)
package testing;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
public class IconTest {
public static void main(String[] arguments) throws IOException {
JFrame frame1 = new JFrame();
frame1.setTitle("Frame1");
frame1.setSize(500, 500);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
frame1.setLayout(flo);
//POSSIBILITY 1 TO HANDLE IMAGE
InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
Image image = ImageIO.read(resourceAsStream);
JLabel label1 = new JLabel(new ImageIcon(image));
//POSSIBILITY 2 TO HANDLE IMAGE
/* java.net.URL url= IconTest.class.getResource("strawberry.jpg");
BufferedImage watermarkImage = ImageIO.read(url);
JLabel label1 = new JLabel(new ImageIcon(watermarkImage));*/
frame1.add(label1);
frame1.setVisible(true);
}
}
Put the image where you have the source file because it points to the source directory
InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
and then generate runnable jar file and then right click the jar and give run as java platform binary
POSSIBILITY 3 TO HANDLE IMAGE :
You can check that resource that you are fetching is exist or not. It resource not found then you can create JLabel with alternative text also...
JLabel label1 ;
URL imageUrl = IconTest.class.getClassLoader().getResource("strawberry.jpg");
if ( imageUrl != null ) {
label1 = new JLabel(new ImageIcon(imageUrl));
} else {
label1 = new JLabel("Alternative text");
}
Following Maven standard directory layout might be helpful:
InputStream resourceAsStream = IconTest.class.getResourceAsStream("/strawberry.jpg")
It should start from "/". Also check whether the jar actually have the image. Just unpack it and check whether the image is actually added.
The guidance offered here in troubleshooting the problem helped greatly - thank you to everyone. I tested contents of an exported JAR; I used diagnostic code suggested by Kishan to determine if my code could "see" the image. I believe it might have something to do with the way Eclipse works/refreshes if I move images around in the file system instead of the Eclipse import function.
Finally, in order to get it to work, I made the following changes:
I created a new project and two sub-packages - one for 'resources' and one for my code class. Then I right-clicked > import on the resources package in Eclipse to get the image.
The only thing to change in my code is ....getResourceAsStream("/resources/strawberry.jpg");
I have been searching the internet, but I can't find a solution for this. My program works fine in Eclipse, but I have to make the program into a .jar file so the user can just click on the .jar file and the GUI will run.
When I click on the .jar file that I exported, nothing happens. There is just the main class of the program and if I click run in Eclipse, the GUI will come up.
What do I need to add in here so the GUI will stay and not disappear straight away? I tried to put a JOptionPane in there and it works, the box will come out but the GUI will not still.
package dijkstra;
import java.awt.BorderLayout;
import java.util.Map;
import javax.swing.JFrame;
public class RunGUI {
public static void main(String[] args){
FlightSchedulerGUI.setWindowsLookAndFeel();
try {
Map<Integer, Airport> airports = FileProcess.loadtegMap();
FlightSchedulerGUI GUI = new FlightSchedulerGUI(airports);
GUI.randomizeRoute();
GUI.findBestRoute();
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(GUI);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Flight Scheduler");
frame.setSize(600,400);
frame.setVisible(true);
} catch(Throwable t ){
t.printStackTrace();
System.err.flush();
System.exit(1);
}
}
}
Ensure you have added the Main-Class attribute to the MANIFEST file of your jar file.
Example:
Main-Class: dijkstra.RunGUI
The file must be called MANIFEST.MF and must be placed to META-INF folder, within your jar file.
More info
package mainClasses;
/*
* Frame Info and all that ****,
* mainFrame is the actual frame itself
* it will refer to MainC.java a lot Main class = Main Class
*/
import java.awt.FlowLayout;
import java.awt.Graphics;
import JavaGame.src.resources.*; //Problem Code
import javax.swing.JButton;
import javax.swing.JFrame;
public class mainFrame extends JFrame {
private static final long serialVersionUID = 1L;
public mainFrame() {
JButton playButton = new JButton();
JButton infoButton = new JButton();
JButton exitButton = new JButton();
int x = 300, y = 300;
setSize(x, y);
setVisible(true);
setLayout(new FlowLayout());
setTitle("Kingdom Raider");
setDefaultCloseOperation(EXIT_ON_CLOSE);
/*Buttons and Properties*/
playButton.setBounds(x, y, 200, 100);
playButton.setText("Play!");
add(playButton);
infoButton.setBounds(x, y, 200, 100);
infoButton.setText("Information");
add(infoButton);
exitButton.setBounds(x, y, 200, 100);
exitButton.setText("Exit");
add(exitButton);
/* Add image here */
}
public void Painting (Graphics g) {
//Me.
}
}
I'm creating a game and I'm having an import problem.
As you can see I want to import JavaGame.src.resources, as I'm trying to import an img.
Here's how my Directory stands:
I don't need to know the code on resourcesmanager.java its blank at the moment.
So basically, this class here is in packages mainClasses, but i want to access the resources package. What gives?
Your package name is resources, so write this:
import resources.*; // No-Problem Code
The remaining parts of the directory structure is specific to Eclipse and doesn't have anything to do with Java classpaths
Your source folder is src, so this is the root of your class hierarchy. You should do
import resources.*
However using * is bad form and you should try and import only classes that you need in this particular class, like you've done with javax.swing.JButton for example. So:
import resources.ResourceManager;
Resources aren't imported like packages. Have a look here: http://docs.oracle.com/javase/1.5.0/docs/guide/lang/resources.html.
Specifically, here's an example how to load images from resources: http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource.
Eclipse will automatically import stuff for you if you copy and paste something-maybe you could write a short clip that uses something in JavaGame.src.resources, and then copy paste that-eclipse will do the rest.
I think this could be a problem with Eclipse configuration. Sometimes Eclipse considers the source folder in the project as part of the package. Just delete the project from the Eclipse workspace without deleting it from the file system and import it again.
That should help.
Deleting project from eclipse without deleting it from the file system:
http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-42b.htm
Importing existing project into eclipse:
http://agile.csc.ncsu.edu/SEMaterials/tutorials/import_export/
What you want to do is access the files stored in your resources folder. To do this, you don't import the folder as you tried to do. Instead, do what Tony the Pony advised and use
getResource("FileName.ext")
As an example, to turn a file into an icon, you'll have to use the resource path:
java.net.URL path = this.getClass().getResource("FileName.jpg");
ImageIcon icon = new ImageIcon(path);
I should also point out that if you're using NetBeans, you need to add the resource folder as a source folder; otherwise the project won't compile how you want it to, resulting in a .jar file that can't access the resource files. Eclipse might be similar. To add the folder as a source:
Right click on project
Select properties
Click "Sources" in categories pane
Click "Add Folder" and select the resource folder you made