I'm completely clueless and lost. I recently started programming on Java. I wanted to make a program that displayed an image that the user could click (a button with an image) and in return play a sound. I've watched many tutorials and they don't work when I follow them. Also I don't know whether I should use swing or javaFX or awt, or if I need to make a new file for the images and buttons only. Please help.
-
Is this your first program? – Rabbit Guy Apr 27 '16 at 19:41
-
Easiest way would be to create a rectangle around the image, and then have a point being the mouse location and using the Rectangle class' .contains() method. Flip a boolean here to do what you would like. – 2ARSJcdocuyVu7LfjUnB Apr 27 '16 at 19:49
-
2`I'm completely clueless and lost.` - well start with the Swing tutorial on [How to Use Buttons](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html) for working code and explanations. `I've watched many tutorials and they don't work when I follow them` - well download the tutorial code and test the program. If there is something you don't understand then ask a specific question. We can't possibly guess what you find confusing from the other tutorials. – camickr Apr 27 '16 at 20:38
6 Answers
Here is a sample using JavaFX. Your question is tagged Swing, but the question text mentions you are considering JavaFX, so I thought I'd provide this solution so that you could see what a JavaFX style implementation would look like.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.*;
import javafx.scene.layout.StackPane;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;
public class ImageAudioPlayer extends Application {
private static final String BUTTON_ICON_LOC =
"http://icons.iconarchive.com/icons/mirella-gabriele/fantasy-mediaeval/128/Poison-red-icon.png";
private static final String AUDIO_FILE_LOC =
"http://soundbible.com/mp3/Power_Up_Ray-Mike_Koenig-800933783.mp3";
@Override
public void start(Stage stage) throws Exception {
final AudioClip audioClip = new AudioClip(AUDIO_FILE_LOC);
final ImageView graphic = new ImageView(new Image(BUTTON_ICON_LOC));
Button button = new Button(null, graphic);
button.setStyle("-fx-base: mistyrose;");
button.setOnAction(event -> audioClip.play());
StackPane layout = new StackPane(button);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I don't really know Swing, so I won't provide a solution for that. Library recommendations are off-topic for StackOverflow, so I won't provide a library recommendation here and encourage you to do your own research into potential technologies and decide on the best match that suits your application requirements and skill set.
-
1*"Library recommendations are off-topic for StackOverflow"* - Then you should have voted the question as off-topic – MadProgrammer Apr 27 '16 at 21:02
-
... or you could have given information about the library you're thinking about, as you made me curious :) – Matthieu Apr 28 '16 at 09:08
-
Needs a few changes to work with Java 7 (no lambda and `new StackPane(); layout.getChildren().add(button);`) but finally a JavaFX example I can play with, thanks! :) I'll edit my answer to make the same in Swing. – Matthieu Apr 28 '16 at 09:27
Search more: it has an answer here:
Icon img = new ImageIcon("/class/path/to/image.png");
JButton btn = new JButton(img);
Make sure /class/path/to/image.png
is in the classpath. If it's an image from your hard drive you'll have to load it first, as described in the answer I linked.
Edit: @jewelsea example in JavaFX into Swing:
public class ImageAudioPlayer extends JFrame {
private static final String BUTTON_ICON_LOC =
"http://icons.iconarchive.com/icons/mirella-gabriele/fantasy-mediaeval/128/Poison-red-icon.png";
private static final String AUDIO_FILE_LOC =
"http://soundbible.com/grab.php?id=1019&type=wav";
public ImageAudioPlayer() throws MalformedURLException {
super("Audion button");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
Icon icon = new ImageIcon(new URL(BUTTON_ICON_LOC));
JButton button = new JButton(icon);
cp.add(button, BorderLayout.CENTER);
button.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
playAudio();
}
});
}
private void playAudio() {
// Not nearly as easy as JavaFX, and cannot play MP3
try {
URL url = new URL(AUDIO_FILE_LOC);
final Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
clip.start();
clip.addLineListener(new LineListener() {
@Override public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws MalformedURLException {
ImageAudioPlayer iap = new ImageAudioPlayer();
iap.pack();
iap.setVisible(true);
}
Personally I've been experimenting with Swing lately and I think it's rather intuitive, at least at the base level. What you want is something along the lines of an image object with an added listener for reactions for clicks/whatever it is you wish to react to. Something like this: Adding a mouse listener to image or image Icon in java
alternatively you could use the built in button objects in the swing libraries and set an image to it. You would still need to configure the listener to do whatever it you wish it to do. Along these lines: How do I add an image to a JButton

- 1
- 1

- 594
- 1
- 7
- 17
You should either use Swing or JavaFX...
AWT is very old and should not be used unless there is no other way (I heard that sometimes on OSX there are some issues with Swing...).
Swing is the most common GUI-Toolkit in java, but Oracle announced, that JavaFX will completely replace Swing.
In my opinion Swing is easier to start, because there are tools like the eclipse window builder, which enables you to create your application in a graphical interface, but JavaFX is more likely to be used in the future, because it has some great improvements over Swing (like CSS skins etc.).
So you'll basically have to decide what you like more:
JavaFX will be the Toolkit in the Future - Swing is - still - the mostly used one, with more support etc.
And if you are using Swing, I think a JLabel can contain an image - if you add an mouseClicked listener that's probably the way to go...

- 1,186
- 1
- 10
- 37
You can wrap an image object inside of an anchor tag:
<a href="http://www.w3schools.com"><img src="pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px;"></a>

- 5
- 3