I have found plenty of threads on this subject but i still dont get it to work. It works easily from the compiler but not from the jar file. It seems the jar file finds the audio file but it just doest play it.
import sun.audio.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
#SuppressWarnings({"serial","restriction"})
public class JarSoundTest1 extends JFrame {
JButton button;
InputStream in;
AudioStream as;
public JarSoundTest1() throws Exception {
JOptionPane.showMessageDialog(null, this.getClass().getResource("blopp.wav"));
button = new JButton("Click to Blopp!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
in = this.getClass().getResourceAsStream("blopp.wav");
as = new AudioStream (in);
AudioPlayer.player.start(as);
JOptionPane.showMessageDialog(null, "try");
}catch(Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "catch");
}
}
});
add(button);
}
public static final void main(String[] args) throws Exception {
JFrame frame = new JarSoundTest1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
The JOptionPane displays "try" every time the button is clicked, indicating the file is found i assume? Still no sound is played. I have tried using audio files placed both inside and outside the jar file. Help to understand this is much appreciated.
Ok, I got it finally. I don't think it is a sound issue I am quite sure as I can get a wav to play with code very similar to yours, it is a resource issue within jars which can be quite tricky. I would suggest the following based upon experiments in editing the above code:
getClass vs getClassLoader
If you use getClass, the path must begin with the forward slash, /. So, if your .wav is at the top level, ./blopp.wav is the way to go. So likely that is the only adjustment you will need if the .wav file is recognized by sun.audio.*.
If you can find the resource in the jar, but cannot hear audio, maybe try a different .wav file. Some good wav files are here
Related
I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.
Completely new to programming and studying it right now at a university. This might seem easy but they literally showed us nothing on how to program so this task is hard for me to do. So maybe someone here can help me understand how I can do this:
The task:
Create a method called "open(String fileName)" that creates and opens a text file with the name fileName
Create a method called "pageStart()" that writes "html" into the file
There are a lot more methods I have to create but all of them should be easy if I understand how the "pageStart()" one works.
package exporter;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class HTMLCreator {
public static void main(String[] args) {
open("Hello.txt");
}
public static void open(String fileName) {
File file = new File(fileName);
try {
// Creates new file
if (file.createNewFile()) {
}
// Opens file
Desktop desktop = Desktop.getDesktop();
if (file.exists())
desktop.open(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Ok so that does create a .txt file and opens it. So far so good.
Now the problem. I have to create a method that WRITES into that .txt file and I have NO clue how to do that.
What I tried until now:
public static void startPage() {
FileWriter fw = new FileWriter(file)/*<-- obviously won't work but I don't know how it would work...*/;
fw.write("<html>");
fw.close();
}
I know that this obviously won't work since the file that I want is not in that method. How do I do that?
How do I make it so my startPage() method writes into the Hello.txt file I created earlier?
I would appreciate help a lot!!!
My question is not about how to create and write into a textfile! My question is more how you combine two methods to do this! It would help immensely if someone could write two methods for me, one that creates and opens a textfile and another method that writes into the textfile that the first method created and opened. That would most likely solve my problem!
I'm currently trying to develop a game, and the file path is changing when I export it.
Here is the code:
package random;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Troll extends JFrame{
/**
*
*/
private static final long serialVersionUID = 4176461585360667597L;
public static BufferedImage img;
public static void main(String[] args){
File f = new File("troll.png");
try{
if(f.exists()){
System.out.println("ITS THERE! :D");
img = ImageIO.read(f);
} else {
System.out.println("DOESNT EXIST, REAL PATH IS: " + f.getAbsolutePath() );
}
}catch(Exception e){
e.printStackTrace();
}
new Troll();
}
public Troll(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public void paint(Graphics g){
g.drawImage(img, 500, 350, this);
}
}
When I run it through Eclipse ( The IDE I'm using ), it's running fine and it's showing the image. When I export it as a jar and convert it to an exe using Jar2Exe Software, the image does not appear and in the console it says that the absolute path for the image is on my Desktop. But when I open the exe using 7-Zip, the picture is in the exe.
How can I export it so that when the user runs it, the program can find the file path and show the image, instead of it thinking that it's on my desktop?
If you want to publish it as a jar then you need to use the Jar-specific API for reading your file. See eg. How to read a file from a jar file? (and you need to configure Eclipse to put the picture in the jar, which it sounds like you're already doing).
Also you should let us know whether it works when it's in a jar but not as an exe, that will help us narrow down where the problem may be.
I hope this is not a troll (lol)
img = ImageIO.read(this.getClass().getResource("/troll.jpg"));
You are in a jar, there is no resource file.
See that link as well: http://www.jar2exe.com/createdexe/integrate/protect
Thread.currentThread().getContextClassLoader().getResource("hello/yes.gif");
I am trying to put the play method within my Audioapp class inside my ActionListener, I tried putting it in but got errors.
I have read the javadoc on ActionListener but could not find it
This is my audio:
public class Audioapp extends JApplet // find out how to implement play method into action listener?
{
public class Sound // Holds one audio file
{
private AudioClip song; // Sound player
private URL songPath; // Sound path
Sound(String filename)
{
try
{
songPath = new URL(getCodeBase(),"G:\\Uni\\Programming\\Rolling assignements\\Week0\\Programming week21"); // This is the place were im getting error
song = Applet.newAudioClip(songPath); // Load the Sound
}
catch(Exception e){e.printStackTrace();}
}
public void playSound()
{
song.play(); // Play
}
}
}
And this is my actionListener:
class PlayStoHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String computerRand = sps.computerChoice();
txtComputerRand.setText(computerRand);
String result = sps.play(Sps.ROCK);
txtResult.setText(result);
scis.setVisible(false);
open.setVisible(false);
stone.setVisible(true);
pap.setVisible(false);
win.setVisible(false);
none.setVisible(false);
lose.setVisible(false);
if (result == "User Wins"){
win.setVisible(true);
song.play(); // here i tried putting the song.play in this if section, the error I got was "song cannot be resolved"
}
else if (result == "Draw"){
none.setVisible(true);
}
else {
lose.setVisible(true);
}
}
I'm a beginner so it's most probably a very stupid basic error
Any help would be appreciated
songPath = new URL(getCodeBase(),"G:\\Uni\\Programming\\Rolling assignements\\Week0\\Programming week21");
The URL constructor expects the second string to represent a relative URL, whereas you have put a file path. URLs always have forward slashes, and a file: based URL there would make little sense (the WAV is hosted on your site, not the HD of the end user).
If the applet is being loaded by HTML at the root of the site with no codebase declared in the HTML, and the wav is called moo.wav and is located in a sub-directory named Week0/Programming week21 the correct path would be:
songPath = new URL(getCodeBase(),"Week0/Programming week21/moo.wav");
But to make things a lot simpler, at least for the moment, put the HTML, the applet and the clip in the same directory and use:
songPath = new URL(getCodeBase(),"moo.wav");
song is private. You created a method to play the sound so use it.
Get the instance of your Audioapp and run the playSound() method.
After thinking I was on course to solving a problem with making text (read from a file) appear in a JPanel, I`m frustratingly back to square one.
The code is below. The result is just a blank screen 400x500 screen. Some combinations of using nextLine() + nextLine() as displayText commands result in one word coming up from the file (the word has been different multiple times). This makes me wonder: do I need code that deals with text wrapping? The textfile itself is in paragraphs, and as such, I thought that sf.displayText should say sf.displayText(reader.next() + reader.nextline() + reader.nextline(), and have tried other combinations, but this may be confusing the while parameters. Have also tried a different textfile with simple sentences, no paragraphs, but again, nothing comes up.
Having looked online, I have found that layouts may be an issue, and that alternative options may be BufferedReader or using JTextArea. Browsing through Big Java didn`t provide anything I felt I could take, as all discussion on the scanner went towards integers, whereas the file I want read is prose. I also tried putting a small piece of text in the code itself and cancelling out everything else below it to see if I could transfer text from the code to the JPanel:
StoryFrame sf = new StoryFrame();
sf.displayText("Life is beautiful");
but still nothing came up. Ultimately, I want to put text from a file into a JPanel, and have each paragraph come up 5 seconds after the one before. So ultimately, my questions are:
Why does my text fail to show up, or only display one word? Is it because I don`t specify a layout?
Do I need to think about text wrapping?
Should I look into JTextArea instead of JPanel, and BufferedReader instead of Scanner?
Have I been using the nextLine method from the Scanner correctly?
Can I put a command to read a file and display that file`s text in the display
method of StoryFrame (I think this would make things a lot easier)?
I know it`s a lot, so any answers to any of the questions would be greatly appreciated, thank you.
Tom
import javax.swing.JFrame;
import javax.swing.JLabel;
public class StoryFrame extends JFrame {
private JLabel mylabel;
public StoryFrame() {
setTitle("見張ってしながら...");
setSize(400,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
mylabel = new JLabel();
this.add(mylabel);
setVisible(true);
}
public void displayText(String text) {
JLabel storyText = new JLabel();
add(storyText);
}
}
ShowIntro
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class ShowIntro {
public static void main(String args[])
throws IOException {
StoryFrame sf = new StoryFrame();
Scanner reader = new Scanner(new File("Try.txt"));
while (reader.hasNextLine()) {
//String line = in.nextLine() Not sure whether this would contribute, I doubt it does though
sf.displayText(reader.next());
//sf.displayText(reader.next() + reader.nextLine() + reader.nextLine()); was also attempted.
try {
Thread.sleep(5000);
} catch (InterruptedException e) { }
}
}
}
it fails because you never call a method to use the text in your displaytext method
public void displayText(String text) {
mylabel.setText(text);
}
You are also reading the file one word at a time:
sf.displayText(reader.next());
should be:
sf.displayText(reader.nextLine());
if you want to read upto the next newline character.
Even though this was not in the original question to satisfy some of the comments below here is a modified version of the program
package com.vincentramdhanie.kitchensink;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class StoryFrame extends JFrame {
private JTextArea area;
public StoryFrame() {
setTitle("見張ってしながら...");
setSize(400,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
area = new JTextArea(10, 30);
area.setEditable(false);
area.setCursor(null);
area.setOpaque(false);
area.setFocusable(false);
this.add(area);
setVisible(true);
}
public void displayText(String text) {
area.setText(text);
}
public static void main(String args[])
throws IOException {
StoryFrame sf = new StoryFrame();
Scanner reader = new Scanner(new File("Try.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
sf.displayText(line);
try {
//to skip blank lines. If the line has no non-space characters then do not sleep
if(!line.trim().equals("")){
Thread.sleep(5000);
}
} catch (InterruptedException e) { }
}
}
}