I want to display information about the musical composition in the browser via Java applet. I use the library beaglebuddy_mp3.jar for id3 tags. A folder with files looks like this:
applet
- index.html
- FirstApplet.class
- beaglebuddy_mp3.jar
In index.html I connect an applet:
<applet code="FirstApplet.class" archive="beaglebuddy_mp3.jar" width="500" height="500"></applet>
FirstApplet.class contains the following code:
import java.applet.Applet;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import com.beaglebuddy.mp3.MP3;
public class FirstApplet extends Applet{
public void paint(Graphics g){
try {
MP3 mp3 = new MP3("D:\\Music\\abc.mp3");
g.drawString(mp3.getBand() +" "+mp3.getTitle(), 20, 20);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
After starting the index.html file dialog box appears with a warning stating that I run the application at your own risk. Then I click "Run", instantly appears and disappears gray square. On that nothing is displayed.
Try the following:
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import java.io.File;
import java.io.IOException;
import com.beaglebuddy.mp3.MP3;
public class FirstApplet extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
MP3 mp3 = new MP3("D:\\Music\\abc.mp3");
JLabel label = new JLabel(mp3.getBand() +" "+mp3.getTitle());
add(label);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
And secondly you have to sign your applet code with an official certificate to be able to run it in your web browser.
Related
I'd like to type: "/ammo" when I type ALT+A.
The program runs but it seems like to stop right after the running:
I press alt+A or A and the code is not doing anything at all.
package jnativehook01;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Example implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("A")) {
try {
GlobalScreen.unregisterNativeHook();
Robot bot;
try {
bot = new Robot();
String text = "/ammo";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
//type: /ammo
bot.keyPress(KeyEvent.VK_T);
bot.keyRelease(KeyEvent.VK_T);
} catch (AWTException e1) {
}
} catch (NativeHookException e1) {
}
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}
public static void main(String[] args) {
new Example();
}
}
Ok, now it's working:
package jnativehook01;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import java.util.logging.*;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
public class Example implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("A")) {
Robot bot;
try {
String text = "/ammo";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
bot = new Robot();
for (int i = 0; i < 10; i++) {
//t
bot.keyPress(KeyEvent.VK_T);
bot.delay(100);
bot.keyRelease(KeyEvent.VK_T);
bot.delay(500);
bot.keyPress(KeyEvent.VK_CONTROL);
bot.keyPress(KeyEvent.VK_V);
bot.keyRelease(KeyEvent.VK_V);
bot.keyRelease(KeyEvent.VK_CONTROL);
bot.delay(500);
//Enter
bot.keyPress(KeyEvent.VK_ENTER);
bot.keyRelease(KeyEvent.VK_ENTER);
bot.delay(1000);
bot.keyPress(KeyEvent.VK_ENTER);
bot.keyRelease(KeyEvent.VK_ENTER);
bot.delay(400);
}
} catch (AWTException e1) {
}
}
}
public void nativeKeyReleased(NativeKeyEvent e) {
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
public static void main(String[] args) {
Example ex = new Example();
try {
GlobalScreen.registerNativeHook();
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.OFF);
} catch (NativeHookException eb) {
System.out.println(eb.getMessage());
}
GlobalScreen.addNativeKeyListener(ex);
}
}
There are still a few problems with your code.
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("A")) {
This is not the correct way to check for the A key. This will check to see if AWT produces the ascii 'A' for that key. These values could be overridden by the JVM at runtime. You should check for the NativeKeyEvent.VK_A constant. You also fail to check for the ALT flag on that key event. Something like the following is more of what you are looking for.
if (e.getKeyCode() == NativeKeyEvent.VC_A && e.getModifiers() & NativeInputEvent.ALT_MASK) {
A note on thread safety. You are relying on AWT inside of the key callback, however, this library does not use AWT to dispatch events by default. You need to take a look at the Thread Safety section of the wiki for Thread Safe examples.
You may choose to replace the Robots class with GlobalScreen.postNativeEvent(...) for convenience, to omit Swing/AWT, but it is not required.
A note on blocking inside of the event listener callback. If you block inside this function, via sleep or other long running process, you may cause a delay in key event delivery by the OS or worse, library removal by some operating systems. This removal is outside the control of the library and controlled by the OS.
I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
I've written a program that has to open an image I've placed on the desktop. The problem is that the program runs but nothing happens in the console nor does it open the image. Do I've to implement a GUI to fix the problem or...?
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Image {
public JavaImage() {
try {
BufferedImage image = ImageIO.read(new File("C:/Users/Username/Desktop/index.jpg"));
}
catch (IOException e) {
System.out.println("There isn't a picture in the folder");
}
}
public static void main(String[] args) {
new Image();
}
}
I am trying to create a program using applets in NetBeans and I am having a problem. Whenever I try to run a program it says "Project does not have main class set". I was able to get around this by adding
public static void main (String[] args) but my program doesn't do anything. I tried just a generic program to see if it was my coding and it still didn't work. Do I need to reset my NetBeans or is it a coding error?
Here is the code I got from the Oracle website that doesn't work
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class HelloWorld extends JApplet {
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
This is the code for my program:
package robot;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JApplet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.lang.Object;
public class Robot extends JApplet {
private Rectangle rect;
public void init(){
rect = new Rectangle (0, 0, 20,20);
this.addKeyListener((KeyListener) this);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.white);
g.fillRect(0,0,500,500);
{
this.setSize(355, 355);
}
Graphics2D g1 = (Graphics2D) g;
g1.setColor(Color.black);
g1.fill(rect);
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()== KeyEvent.VK_UP) {
rect.setLocation ( rect.x,rect.y=+20 );
repaint();
}
if (e.getKeyCode()== KeyEvent.VK_DOWN) {
rect.setLocation ( rect.x,rect.y=-20 );
repaint();
}
if (e.getKeyCode()== KeyEvent.VK_RIGHT) {
rect.setLocation ( rect.x =+20, rect.y );
repaint();
}
if (e.getKeyCode()== KeyEvent.VK_LEFT) {
rect.setLocation ( rect.x =-20,rect.y);
repaint();
}
}
}
I was able to run the program if I right clicked in my code then hit "Run Project" but whenever I try and use the run project button it doesn't work.
The second way used to run it simply isn't valid for an applet. That is for an application.
You can set main class by left click on project -> run and select main class:
In the following code, I call JOptionPane.showMessageDialog, inside a try/catch block. But when the error is caught, my JOptionPane is visible but without any message !!! Does someone knows why and how I can correct the problem ?
Regards
MyBoardJPannel.java
package experimentations.gui;
import java.awt.Graphics;
import java.awt.Image;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MyBoardPannel extends JPanel {
#Override
public void paint(Graphics grahics) {
if (imageToShow == null)
imageToShow = loadImage("sampleImage");
}
/**
* In fact, there are not any image in project => will go to catch clause.
* #param imageName
*/
private void loadImage(String imageName) {
InputStream imageStream = getClass().getResourceAsStream("/"+imageName+".png");
try {
imageToShow = ImageIO.read(imageStream);
}
catch (Exception e) {
String errorMessage = "Failed to load image "+imageName;
System.err.println(errorMessage);
JOptionPane.showMessageDialog(this, errorMessage,
"Image loading error", JOptionPane.ERROR_MESSAGE);
imageToShow = null;
System.exit(1);
}
}
private Image imageToShow;
}
JOptionPaneErrorShowing.java
package experimentations.gui;
import javax.swing.JFrame;
public class JOptionPaneErrorShowing extends JFrame {
public JOptionPaneErrorShowing(){
setTitle("JOptionPane experimentation");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(new MyBoardPannel());
}
/**
* #param args
*/
public static void main(String[] args) {
new JOptionPaneErrorShowing().setVisible(true);
}
}
It's likely a Swing concurrency issue. But more importantly, you should never load an image from within a paint or paintComponent method, ever. Read it in the constructor or elsewhere but paint/paintComponent need to be lean and blazingly fast.
To solve your issue, consider reading in the image in SwingWorker object. If you call a JOptionPane from within the SwingWorker's doInBackground method though, be sure to call it on the Swing event thread, the EDT, using SwingUtilities.invokeLater(Runnable).
Also, you will hardly ever want to draw in a JPanel's paint method unless you are taking care of painting borders and children. Instead paint in a paintComponent method, and don't forget to call the super.paintComponent(g) method in that paintComponent override. You'll want to read the Swing graphics tutorials as this is all spelled out there.
For example:
import java.awt.Graphics;
import java.awt.Image;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class MyBoardPannel extends JPanel {
protected static final String SAMPLE_IMAGE = "sampleImage";
Image imageToShow = null;
public MyBoardPannel() {
SwingWorker<Image, Void> mySW = new SwingWorker<Image, Void>() {
#Override
protected Image doInBackground() throws Exception {
return loadImage(SAMPLE_IMAGE);
}
#Override
protected void done() {
try {
imageToShow = get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
};
mySW.execute();
}
#Override
public void paintComponent(Graphics grahics) {
super.paintComponent(grahics);
if (imageToShow != null) {
grahics.drawImage(imageToShow, 0, 0, null);
}
}
private Image loadImage(String imageName) {
InputStream imageStream = getClass().getResourceAsStream(
"/" + imageName + ".png");
try {
return ImageIO.read(imageStream);
} catch (Exception e) {
final String errorMessage = "Failed to load image " + imageName;
System.err.println(errorMessage);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(MyBoardPannel.this, errorMessage,
"Image loading error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
});
}
return null;
}
}
I don't really know, but maybe your panel you use as parent of the JOptionPane (by passing this) is invisible or there is something else wrong. Try adding pack(); at the end of your JOptionPaneErrorShowing constructor.
What I know is that I had this problem when I was using an old Ubuntu and old Nvidia driver for my GPU, when the desktop effects were turned on (the Compiz Fusion of today. I don't know if it was already called Compiz, that long ago).
Aha! I found it, you are displaying the error inside the repaint method. Never do that! Load your image inside the constructor of the MyBoardPanel class and show error messages over there.