简体   繁体   English

如何制作可点击的图片?

[英]How to make a clickable image?

I'm completely clueless and lost. 我完全一无所知,迷路了。 I recently started programming on Java. 我最近开始用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. 另外,我也不知道是否应该使用swing或javaFX或awt,或者是否仅需要为图像和按钮创建新文件。 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. 确保/class/path/to/image.png在类路径中。 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: 编辑 :将JavaFX中的@jewelsea示例转换为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. 这是使用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. 您的问题被标记为Swing,但问题文本中提到您正在考虑使用JavaFX,因此我想提供此解决方案,以便您可以看到JavaFX样式实现的外观。

爱情魔药

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. 我不太了解Swing,所以我不会为此提供解决方案。 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. 库建议对于StackOverflow来说是不合时宜的 ,因此在这里我不会提供库建议,并鼓励您对潜在技术进行自己的研究,并确定最适合您的应用程序要求和技能的匹配项。

Personally I've been experimenting with Swing lately and I think it's rather intuitive, at least at the base level. 就我个人而言,最近我一直在尝试Swing,并且我认为它相当直观,至少在基础级别上是如此。 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 像这样: 在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 遵循以下原则: 如何将图像添加到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 : 我认为,如果您是初学者,则可以从swing和netbeans开始: 是一个简单的教程,如何在swing中处理图像:

Other good tutorials: 其他好的教程:
text : here 文字: 这里
video: here 视频: 这里

You should either use Swing or JavaFX... 您应该使用Swing或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...). AWT非常老,除非没有其他方法,否则不应该使用(我听说有时候在OSX上Swing会出现一些问题...)。
Swing is the most common GUI-Toolkit in java, but Oracle announced, that JavaFX will completely replace Swing. Swing是Java中最常见的GUI-Toolkit,但是Oracle宣布JavaFX将完全取代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.). 在我看来,Swing易于启动,因为有诸如eclipse window builder之类的工具,它使您可以在图形界面中创建应用程序,但是JavaFX将来更可能被使用,因为它相对于摇摆(例如CSS皮肤等)。

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. JavaFX将成为将来的工具包-Swing仍是-仍然是最常用的工具包,并提供更多支持等。

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... 如果您使用的是Swing,我认为JLabel可以包含一个图像-如果您添加mouseClicked侦听器,则可能是这样。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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