Set icon in JFrame - java

I want to change the icon of the project instead of java icon. When the program icon is being displayed in status bar, it should be displaying the customized icon instead of default java icon.
I am using the following code. Please suggest me what's wrong in this code.
class newframe extends JFrame
{
Container cp;
newframe()
{
cp=this.getContentPane();
cp.setLayout(null);
}
public static void main(String args[])
{
newframe frm= new newframe();
frm.setbounds(0,0,1000,800);
frm.setVisible(true);
ImageIcon im1= new ImageIcon("path upto image");
frm.setIconImage(im1.getImage());
}
}

..new ImageIcon("path upto image");
A frame icon will typically be an embedded-resource, so must be accessed by URL rather than (a String representing a path to) a File.

There are a couple of things that would be keeping it from compiling. First:
frm.setbounds(0,0,1000,800);
Your "setbounds" should have a capital B. Typically, functions will be cased such that the first letter of the first word is lowercased, and subsequent words are upper-cased. See this link for the doc on setBounds: setBounds
There's a second issue in your ImageIcon path. Its hard to say if that came right from your code or if you removed the path for the sake of the example, but Andrew Thompson has addressed that adequately.

I think the problem is the decleration of the imageicon. What you should do is instead of getting the direct path, do something like this:
ImageIcon im1= new ImageIcon("Toolkit.getDefaultToolkit().
getImage(getClass().getResource("path upto image"))");
I do this with all of my applications, and it works every time.

Related

GetClass issue in Java Application Setting Icon

I am trying to do the simple activity of setting the Application Icon in a java application. I have many working examples with me but in this instance it fails. Please help I have tried a) b) c) marked in the code. a) Gives a error hint 'Non-static getClass cannot be referenced from a static context' So I tried b) and c). In both, the program runs, but NO Icon is set, NO errors. (I have put the same image in different paths for test purpose)
private static void createAndShowGUI() {
myFrame = new MyDynamic();
myFrame.setTitle( "Sunsong Public School : Home" );
a)myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("../Images/Sudan.png")));
b)myFrame.setIconImage(ImageIO.read(new File("../Images/Sudan.png")));
c)Image icoon = Toolkit.getDefaultToolkit().getImage("Sudan.png"
Got the solution from some other source. The funny thing is I have dozens of working Applications with Icon. In all of them I am using the Toolkit-getclass-getresources. But in this case I was tinkering with an old code, and stuck inside a static block. From the static context Calling toolkits non-static getClass is NOT working. Had tried hundreds of examples from the net in the last 20 or so hours. Java IO also NOT working complains cannot 'read from file'.
This is the one Finally worked..
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource("Sudan.png"));
Image img = icon.getImage();
myFrame.setIconImage(img); // frame is a JFrame

How to add a seekbar to a video played using vlcj in Java Swing?

I’ve trimmed down the code to only the relevant parts and posted it below. The code works fine. The video plays when you run it but it doesn’t have a seekbar.
public class Screen {
//JFrmae
private JFrame frame;
// Panel which I add the canvas to
private JPanel pVid = new JPanel();
// Canvas
Canvas canvas = new Canvas();
// Embedded Media Player
EmbeddedMediaPlayer emp;
/**
* Create the application.
*/
public Screen() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//Frame
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Adding the panel to the frame
frame.getContentPane().add(pVid);
//Adding the canvas to the panel
pVid.add(canvas);
//Setting canvas size
canvas.setSize(715, 402);
//Loading the VLC native library
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "lib");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
//Initializing the media player
MediaPlayerFactory mpf = new MediaPlayerFactory();
//Misc
emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(frame));
emp.setVideoSurface(mpf.newVideoSurface(canvas));
//Video file name and playing
String file = "video.mp4";
emp.prepareMedia(file);
emp.play();
//pack method
frame.pack();
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen window = new Screen();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I’ve looked for an answer online for the last 4 days. Finally I decided to ask here. The official website for vlcj has pictures of a vlcj player they’ve made. There is a seekbar in those pictures. Link to the webpage which has the pics: http://capricasoftware.co.uk/#/projects/vlcj
They have a number of useful tutorials there but they don’t have any instructions for adding the seekbar.
Then I tried downloading their vlcj-player project from their GitHub page. It showed an error because it couldn’t resolve the “com.google.common.collect.ImmutableList” which is supposed to be imported. (At the moment I’m reading about ImmutableList and stuff and see if there’s a way to fix it.) Since I couldn’t figure that out yet, I looked for a class named seekbar or the like in their project. I couldn’t find any.
I also searched elsewhere online for the answer but I just couldn’t find it. I’d really appreciate any help. Thank you.
Edit:
(This edit is in response to the suggestion given to me by #caprica. Read their comment to this question and my reply to that in the comment to understand what I'm talking about here in this edit. I think it'll be useful for others in the future.)
All right, there must have been some problem with my Eclipse or computer. (I’ll type out how I fixed it at the end of this comment.) It’s working now. I’ll type out what I did step by step so that may be it’ll be useful to others in the future to download and install the project.
Download the project.
Import it as a Maven project. (Import > Maven > Existing Maven Project)
Now in Eclipse right click the imported project and select Run As > Maven Install
And that’s it. Now you can just run the project normally. If you don’t know how to run the project, do it like this. Right click the project and select Run As > Java Application and then Select VlcjPlayer – uk.co.caprica.vlcplayer.
Alternatively you can open the class where the main method is and run it. VlcjPlayer class is where the main method is located. The class is in the package uk.co.caprica.vlcplayer.
The problem I faced was that somehow all the necessary files didn’t get downloaded when I ran it as Maven Install. But it worked fine in another computer. Since I knew where the files are downloaded to, I just copied the folder from that PC and put it in the same place in my PC. The folder name is ‘repository’. It’s location is C:\Users\User Name\ .m2. Perhaps Eclipse in this PC has some problem. I’ll reinstall it later to avoid problems in the future.
And this may be useful, the VLC that’s installed in this PC is 64 bit. Not sure if that makes a difference but mentioning it just in case.
Now that the app is working fine I will see the code and see how the seekbar is made. Thanks a lot #caprica for telling me that I should import it as a Maven project. :)
The Basic Controls tutorial shows the essential approach: Add a panel of buttons to the frame and give each button an ActionListener that invokes the relevant media player command. As an example, this notional Rewind button would "skip backwards 10 seconds (-10,000 milliseconds)."
JPanel controlsPane = new JPanel();
JButton rewindButton = new JButton("Rewind");
rewindButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.getMediaPlayer().skip(-10000);
}
});
controlsPane.add(rewindButton);
frame.add(controlsPane, BorderLayout.SOUTH);
The software design is up to you, but you should at least be aware of
JToolBar, seen here and here.
Action, seen here and cited here.
Timer, seen here as a way to repeat an Action.
All right, guys. I’ve figured out how to do it. I’m not sure how it was done in the official Vlcj project but I’ve figured out my own simple way by learning from the official project.
It just takes a few lines of code. It’s very simple.
These are the steps you have to follow:
Create a JSlider.
To the JSlider, add a mouseMotionListener (‘mouseDragged’ to be exact).
Inside that put in the code which would update the video position based on
the change in the JSlider.
Create a Timer.
Put the code inside it to set the value of the JSlider based on the position
of the video.
And that’s it!
This is the code. It comes inside the initialize() method which you can see in the code I’ve given in the question. (And of course you'll also have to create the JSlider and add it to the panel. I haven't shown the code since it's simple.)
js.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (js.getValue() / 100 < 1) {
emp.setPosition((float) js.getValue() / 100);
}
}
});
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
js.setValue(Math.round(emp.getPosition() * 100));
}
});
timer.start();
Some explanation.
The value you get when you use emp.getPosition always seems to be in decimals. It’s something like 0.1334344 at the start of the video and it’s something like 0.998988 at the end. But the value of JSlider is in int. From 0 to 100. So in the mouseMotionListener added to the JSlider I’ve converted the int value of the JSlider to float by dividing it by 100.
And in the action listener inside the timer I’ve multiplied the value of the video position by 100 and then rounded it off to make it an int value. So that value can be set in the JSlider to make it move in sync with the video.
I’m sure the code is rudimentary and there could be some best practices which I may not have followed. Sorry about that but I’m just getting into java by learning the stuff which I find interesting. Those who are good at java and have used such code in an actual project can comment below with how it can be improved.

How can I get my Image to be displayed using Java?

Well basically my image will not display, i'm almost certain it's my file path
(‪" C:\Users\Alex\Desktop\card.png" is what the image properties say is the file path but unless i put double slashes it confuses them for escape sequences. ) If someone has the answer it will be much appreciated. Here's my code:
import java.awt.*;
import javax.swing.*;
public class IDK extends JFrame {
public static void main(String args[]) {
new IDK();
}
public IDK(){
notsure();
}
public void notsure(){
setBounds(420,100,440,400);
setTitle("Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Tell me something");
JLabel image = new JLabel();
label1.setText("New Text");
JTextField text = new JTextField("Insert text",30);
image.setIcon(new ImageIcon("C:\\Users\\Alex\\Desktop\\card.jpg"));
panel.add(label1,image);
panel.add(text);
add(panel);
validate();
panel.setBackground(Color.CYAN);
setVisible(true);
}
}
There is no problem with using "\" so long as it's escaped, as you have done, if your prefer you can use / instead and on Windows the JRE will correct for it.
How ever, you should be adding the image separately, for example...
image.setIcon(new ImageIcon("C:\\Users\\Alex\\Desktop\\card.jpg"));
panel.add(label1);
panel.add(image);
The way you are doing it now assumes that image is a layout constraint for label1, which it isn't.
You should try and avoid using absolute paths and learn to use relative paths and/or embed the resources within the application context, this makes it easier to locate these resources at runtime.
Create a folder in your project and call it i.e. 'resources' and put your image in that folder. This will ensure that given image is on your classpath and can be easily accessed.
Then you can just do :
new ImageIcon("resources/card.jgp")
Problem with accessing outside resources is that special characters needs to be escaped and also if you export the project and give it to someone else, he/she will not have the image required by software ;)

Making a custom icon for a JFrame

Well I was wondering if I could make an icon image for a JFrame. I do know its posible, because, let me say, I am NOT digging the java logo.
Well if I just hava to use a Frame object I will.
Can someone tell me, I know its possible!
Use an ImageIcon.
ImageIcon icon = new ImageIcon( pathToIcon );
yourFrame.setIconImage(icon.getImage());
Good Luck!
First, you have to have an image file on your computer. It can be named anything. For this example, we will call this one "pic.jpg".
Next, you need to include it in the files that your application is using. For example, if you're using NetBeans, you simply click on "Files" in the left hand side of the IDE (not File as in the menu, mind you). Drag the picture's file over to the folder that houses the main package. This will include it for available use in the code.
Inside the method where you define the JFrame, you can create an image like this:
Image frameImage = new ImageIcon("pic.jpg").getImage();
You can now set it as the IconImage for the frame like this:
JFrame frame = new JFrame("Title");
frame.setIconImage(frameImage);
Hope that's helpful.
Note: the reason that the Image object has to be created like this is because Image is abstract and cannot be instantiated by saying new Image();
Props to you, btw, kid. I wish I would have started learning programming when I was your age. Keep at it!
You can do the following.
public Test {
public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setIconImage(new ImageIcon(Test.class.getResource("image.png"));
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setVisible(true);
frame.setSize(100, 100);
//other stuffs....
}
}

How to add icon into Java (NetBeans) from Mac Os X?

So I'm trying to add an icon into my program, but the textbook I'm reading explain how to only for Windows users. I would like to know how to add the icon. I have it on my program source folder and the code I have so far is something like this:
logo = new ImageIcon("~://resources//CherryBoom.png");
labelone = new JLabel("Fruit No.1 : ", logo, SwingConstants.LEFT);
JPanel panelone = new JPanel();
panelone.add(labelone, logo);
The icon still won't show on the windows panel, so I'm really lost here, and I don't know how can I get it to show into my program.
First of all, check the obvious solutions such as:
Have you done window.add(panelone);
Is the file in the correct spot/url is correct
Secondly, if you hate LayoutManagers like me, but still want to use javax.swing, you might try using drawString and drawImage methods in your panel's paintComponent(Graphics g) class. In detail:
You'll need to make your own JPanel:
public class MyPanel extends JPanel {
as well as override the method:
#Override
public void paintComponent(Graphics g) {
within the method, call this so the window can refresh itself and do other housekeeping things:
super.paintComponent(g);
then, use drawString and drawImage to draw these images in the place you would like them:
g.drawString("Fruit No. 1", x, y);
logo.paintIcon(this, g, x, y);
Whenever you change or draw an image, you'll also want to call in the main method:
panelone.repaint();
Hope this helps!
Java doesn't support expanding the "~" path directive.
Try this...
try {
File file = new File("~");
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
} catch (IOException exp) {
exp.printStackTrace();
}
I think you will find that it doesn't point to the users home folder.
Instead, you should be using System.getProperty("user.home")
logo = new ImageIcon(System.getProperty("user.home") + File.separator + "/resources/CherryBoom.png");
Now, having said that, I would strongly encourage you to use ImageIO over ImageIcon as you will get better feedback when something goes wrong.
Check out Reading/Loading an Image

Categories

Resources