简体   繁体   中英

How to make a clickable image?

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.

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:

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);
    }

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.

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

Setting up an action listener .

I think if you are a beginner you can start with swing and netbeans: here are a simple tutorial how to handle images in swing :

Other good tutorials:
text : here
video: here

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...

您可以将图像对象包装在锚标记内:

 <a href="http://www.w3schools.com"><img src="pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px;"></a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM