How can i play mp4 video file in a JFrame? - java

I want to play a video (mp4) inside a fixed size JFrame. How should I do this? Is there any tutorial or documentation for this?

I guess you could convert your video into a .gif file and then get the audio from that video and play it in the background, it may lower the quality but for simple things it should work.
`import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void audio() {
try {
File file = new File("audio.wav");
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(file));
clip.loop(Clip.LOOP_CONTINUOUSLY);
clip.start();
} catch (Exception e) {
System.err.println("Put the music.wav file in the sound folder if you want to play background music, only optional!");
}
}
private static String arg;
public static void main(String[] args){
arg = "background.gif";
JFrame f = new JFrame();
JPanel p = new JPanel();
JLabel l = new JLabel();
ImageIcon icon = new ImageIcon(arg);
f.setSize(480, 360);
f.setVisible(true);
l.setIcon(icon);
p.add(l);
f.getContentPane().add(p);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
audio();
}
}
https://www.mediafire.com/?18n4iluk9hwitlb Audio.wav
http://www.mediafire.com/view/jx7vogxzsbor0j4/background.gif Background.gif

I think you have use a special framework to do that. You could for example use the Java Media Framework You can download it at the oracle homepage.

The "fixed size(1) JFrame" is easy, or at least it should be. Are you having a specific problem with it? (I ask because it seems odd you should mention it.)
As to support for MP4, the JMF will not handle it. Your best bet is to see what Google throws up for java+mp4. After looking through a few of the top ranked hits, it seems the offerings are not great.
Is MP4 an unchangeable requirement? The JMF can handle many other simpler (older) formats well.
If opening the MP4 in the standard media player is not out of the question - that is as easy as:
Desktop.getDesktop().open(new File("the.mp4"));
(1) And as an end user, have to comment that I detest someone delivering video content to my desktop that cannot be resized. It's my (dang) desktop - I should be able to choose how much of it the video covers!

The JavaFX widget MediaView is able to render an MP4 file. You can embed JavaFX in Swing like this http://docs.oracle.com/javafx/8/embed_swing/jfxpub-embed_swing.htm and then you can use the MediaView like this http://docs.oracle.com/javafx/2/media/simpleplayer.htm

All you really need is a library called vlcj to play any kind of videos on JFrame, since JavaFX's MediaPlayer doesn't support .avi files.
Link to vlcj: https://github.com/caprica/vlcj
(There is also implementation for JavaFX: https://github.com/caprica/vlcj-javafx)

Related

Problems with images when compiled

I have been all over the internet trying to work out how to get an image icon displayed after compiling into a runnable jar. I discovered this problem way too late, I ran my program many times before in eclipse and every thing has worked, now 6 months later with project finished, I compiled my program with eclipse and no audio or images work. Reading on the net, it says about the location of images folder should be inside jar, but mine doesnt get put there?
I have played around with the images folder moving it inside the source folder, but it didn't work. I have a feeling that it might be something to do with the path of the resource...ebut thats only guessing.
I have built a simple program that has the same results... works when ran in eclipse, but not when compiled. Could somebody show me an example by modifying my code below. Thanks in advance.
SOURCE CODE:
package ImageIcon;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Gui {
public static JLabel c;
public Gui(){
JFrame f = new JFrame();
JPanel p = new JPanel();
p.setBounds(0, 0, 120, 200);
p.setBackground(Color.black);
p.setLayout(null);
JPanel bg = new JPanel(new BorderLayout());
bg.setBounds(50, 50, 15, 15);
bg.setBackground(Color.white);
ImageIcon a = new ImageIcon("images/success.jpg");
c = new JLabel(a);
f.setSize(100, 200);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.add(p);
p.add(bg);
bg.add(c);
}
public static void main(String[] args) {
new Gui();
}
}
With your current directory setup, the images dir won't even get built into the jar. Try to extract it and you will most likely see that it's not in there.
You can tell by the fact that it doesn't have the little package logo in the folder, as seen here with resources
The only default directory built into the classpath (/jar) is the src. We need to either put the resources into the src
or configure the build path to include the files that are in the resources. Once we do that, we will see the little package icon inside the folder icon. That's how we know the files are on the build path
CODE we would use:
First Image: Can't, it won't work (this your current predicament)
Second Image:
ImageIcon icon = new ImageIcon(
getClass().getResource("/resources/stackoverflow.png"));
Third Image:
ImageIcon icon = new ImageIcon(
getClass().getResource("/stackoverflow.png"));
To configure the build path to use the third option, follow the instructions in Example 2 in this answer
As from your screenshot, the image exists in a folder called "images". Put it in a folder inside your classpath: src/images/success.jpg and call:
ImageIcon a = new ImageIcon(getClass().getResource("/images/success.jpg"));

I can't run a JFrame due to compiler errors & warnings

*I'm sorry for all of the trouble I may have caused you guys.
So, I am extremely new to programming with just a little experience in Java and Python. I was trying to make a program that would open a frame. In this frame there would be a button. When clicked, this button would play a song. I used a "recommended" code from YouTube. The code would begin to run, and then just stop. No frame would ever even appear. I showed it to a more experienced friend of mine. He said that the exact code ran just fine on his computer. I then sent him a screenshot of my project displayed on eclipse. He said that my JRE seemed to be missing some files. I tried a code that would just create a window, but it had the same problem. I am not sure what the JRE is, but I currently have JRE7. I don't know what I should do to fix this. Please help.
Error List
Severity and Description Path Resource Location Creation Time Id
The public type TopLevelWindow must be defined in its own file TGProject/src Frame.java line 4 1390698271752 73
The type TopLevelWindow is already defined TGProject/src TopLevelWindow.java Unknown 1390699351785 77
The method show(boolean) from the type Component is deprecated TGProject/src sound.java line 16 1390702839525 78
A link to the what my eclipse shows.
http://gyazo.com/3afdfa4f6750420f4e46deec40389340
A link to my Java file.
http://gyazo.com/257481d4ae9e2bb1d0ca93415a6c547e
Code for music
import java.awt.event.*;
import javax.swing.*;
import sun.audio.*;
import java.io.*;
public class sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
//this is outdated, but should still work
frame.show(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e) {
music();
}}
public static void music()
{
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("Jambi.mp3"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error) {}
MGP.start(loop);
}
}
Code for Frame
import java.awt.*;
import javax.swing.*;
// Create a simple GUI window
public class TopLevelWindow {
private static void createWindow() {
//Create and set up the window.
JFrame frame = new JFrame("Simple GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("I'm a label in the window",SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
Error 1
The public type TopLevelWindow must be defined in its own file
You either need to change.
public class TopLevelWindow {
To:
class TopLevelWindow {
Or do as reported and declare a new class for TopLevelWindow
Error 2
The type TopLevelWindow is already defined
I'm not sure what that means, but it might be solved by fixing the first problem.
Warning 3
The method show(boolean) from the type Component is deprecated
For any deprecation warning, go to the relevant method in the Java Docs. They should give details about what to use instead.
Tips
Compile often and ask as soon as you have a single error you do not understand.
Don't try to run code that shows problems in that window. Only experts should even try that.
You catch more flies with honey than with vinegar. Don't take the tone you did with Jayan, even if you think they are being harsh. People help for free, so have little time for questions that do not come up to standard. It might have been better to explain to the person that the question had now changed. Perhaps that would have made no difference to them, but either way, adding that kind of reply discourages everyone from helping.
"I used a "recommended" code from YouTube." Don't use YouTube videos to learn programming. They are often old, and in this case, they are using classes in the sun package for which there were better replacements since Java 1.3.
If you're really that new to programming, I would suggest to use an IDE (development environment) like for instance Netbeans or Eclipse and create a new JFrame form. You can then use the design view to graphically design your interface, IE drag your button on the screen. No need to go around programming frames. All you need to code is the implementation; what happens after you click the button.
After you posted the code, I had another look and this is what I've found:
Both classes have main methods. I ran both and each opened up a different window for me. Typically, you'll only want one main method. It's the main method! It's the starting point of your program and you can of course only have one starting point. At this time, your program is going to do two different things depending on what main method you run.
Still, this isn't your issue, because both mains are running for me. I think you must have the wrong version of java or something?
What I think you did is you pasted all that code into a file that wasn't called exacly "TopLevelWindow". If so, do that. I think your problem will go away.
Remember to only have one class per file, (barring inner classes; not something to concern yourself with as a beginner).

How to change java icon in a JFrame

Ok so I've been researching this one quiet a bit. I am fairly new to java but thought that this one would be easy. Ive tried just about every way that has been answered on this site and still no luck, and usually when I look here I am able to find a answer that fits what I am looking for. Does anyone know how to change the Java icon in the top corner of the JFrame. I'm pretty positive that its not my file path either because all my images are in the same folder and they all work, this is the only one that I can't seem to get to work.
This is the first part my code for the main menu of my program, everything works except when i try to add the icon image. The code I've entered below does not have anything in it for the JFrame IconImage, I removed it since it didn't work. So if there is someone who knows how to get it working with this code that would be highly appreciated, thank you very much in advanced!
public class MainFrame
{
private MyPanel main;
private MyPanel2 create;
private MyPanel3 update;
private MyPanel4 find;
JFrame frame = new JFrame("Main Menu:");
public void displayGUI()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new CardLayout());
main = new MyPanel(contentPane, this);
create = new MyPanel2(contentPane);
update = new MyPanel3(contentPane);
find = new MyPanel4(contentPane);
contentPane.add(main, "Main Menu");
contentPane.add(create, "Create Part");
contentPane.add(update, "Update Part");
contentPane.add(find, "Find Part");
frame.setLocation(200, 200);
frame.setSize(700, 580);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
I have an answer for you. First, make sure that the images are in a folder, not a package. Next, insert this line of code:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/image.png"));
ImageIcon icon = new ImageIcon( );
setIconImage(icon.getImage());
This code gets the image from the class path, and returns it as a image icon, and then it sets it. This should add the image icon to the application. If it doesn't, then tell me.
EDIT: After you told me that that didn't work then I decided to take a second crack at it...
First, put your images into a completely separate folder. I usually call this /res. Next, put your image in there. Now, for loading I took a completely different route. I decided to use ImageIO instead of default loading. To load the image, you use this code:
try {
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
}
catch (IOException exc) {
exc.printStackTrace();
}
ImageIO works a lot better for loading images. If this still doesn't work then please tell me.
If you want to export this as a JAR then put a folder the same name as you used in the program in the same directory as the JAR.
For example in a NetBeans project, create a resources folder in the src folder.
Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource),
you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.
This works pretty fine for me.
Just add this after you've created your JFrame.
try {
Image image = new ImageIcon("/icons/image.jpg").getImage();
frame.setIconImage(image);
}catch(Exception e){
System.out.println("Application icon not found");
}
Paste your image icon (fav.png) in the same package first,
Write following code in constructor of JFrame:
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("fav.png")));
Note:- fav.png is the name of icon
this.setIconImage(new ImageIcon(getClass().getResource("/iconsfolder/iconsname.jpg")).getImage());
// sets the Global icon for the system
try this code put after this code:
public void displayGUI()
{

How to open files in Java Swing without JFileChooser

I'm using Java Swing (GUI) and I want to add a button to my project for opening files.
I don't like the JFileChooser since it opens a small window for browsing through the files of the directories. Can I use something else instead of the JFileChooser under Java Swing?
I've tried to use elements of SWT but it didn't work, meaning is the use of the button object and then use it inside the JFrame, but that failed, so I guess SWT and Swing don't mix together?
Here is the example of Java Swing with JFileChooser and I'm looking for something like this to put in my JFrame.
JFileChooser with the native PLAF seems to fulfill the stated requirement.
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class NativeFileChooser {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
}
});
}
}
Still not quite to your liking? Then you might start with this one & change it to need:
..so I guess SWT and Swing don't mix together?
It is generally not a good idea to mix Swing/AWT/SWT components in the same top-level container. It is not a problem to open an AWT FileDialog over a Swing based JFrame since they are both top-level containers. I am pretty sure the same would apply to Swing/SWT or AWT/SWT.
If you do not need the flexibility of the JFileChooser, you can opt for the FileDialog which uses the native OS file dialog. See also Code ranch topic and this answer on SO

Having difficulty add a custom icon to a JFrame

I have been trying to change the icon in the frame. I have virtually tried everything:
The icon is 16x16 which is the right size ....doesn't work
I've trying PNG,GIF and JPG formats none of them work.
Tried different way of setting the icon....doesn't work.
I've tried relative (local paths) e.g. "icon.gif" and absolute paths e.g. "c:\work\java\icon.gif" ...doesn't work
Here is my code and see if you can figure it out
Thanks
Oli
import javax.swing.*;
public class androidDriver
{
public static void main(String[] args) throws IOException
{
JFrame f = new JFrame("Android Data Viewer");
f.setResizable(false);
f.setSize(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setIconImage(new ImageIcon("androidIcon2.gif").getImage());
}
}
If you put the image in the same directory as the class file then the following should work for you:
f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
Also would suggest setting the icon image before you make the frame visible
f.setIconImage(new ImageIcon(androidDriver.class.getResource("androidIcon2.gif")).getImage());
f.setVisible(true);
I suspect you may have to actually wait for the image to load using a MediaTracker. It's likely that the image is still loading at the point the frame setIconImage references it, so it does nothing.
Have you tried using Toolkit.getDefaultToolkit().getImage("androidIcon2.gif")
And two other things:
Does the image exist? The code you posted will fail silently.
Is it formatted properly? (though I assume Java could handle it if it wasn't)
Make a separate folder next to the source folder then put your image in there, and then use ImageIO to get the image like so:
f.setIconImage(ImageIO.read(new File("res/androidIcon2.gif")));
Also, if that doesn't work, try saving the image as a .png instead of a .gif.

Categories