简体   繁体   English

使用Java GUI将事件处理程序插入图像

[英]Inserting event handler into images using Java GUI

I want to insert an image and then want to add an event to this image using Java GUI. 我想插入图像,然后使用Java GUI向该图像添加事件。 I add the image and then try to insert it into this container but it shows error. 我添加图像,然后尝试将其插入此容器,但显示错误。 Can you please show me which is the right way of inserting an image in Java and then adding a listener to this image or an event handler? 您能告诉我哪种方法是在Java中插入图像,然后向该图像或事件处理程序添加侦听器的正确方法吗? Or if using a container to handle the image is the right way. 或者如果使用容器来处理图像是正确的方法。 How can I do it? 我该怎么做?

This is my code: 这是我的代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;

public class Back extends JFrame { 
    private Container pane;
    public Back() {
        super("title");
        setLayout(null);

        Icon i=new ImageIcon(getClass().getResource("1.png"));
        pane=new Container();

        thehandler hand=new thehandler(); //konstruktori i handler merr 
                                          //nje instance te Background
    }

    private class thehandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {

        }
    }

    public static void main(String[] args) {
        Back  d = new Back() ;

        d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        d.getContentPane().setBackground(Color.GREEN);
        d.setSize(700,500);

        d.setVisible(true); 
    }
}

Here is an example of making a clickable button using a JButton 这是使用JButton制作可点击按钮的示例

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUITemplate {
    JFrame myMainWindow = new JFrame("Title");
    JPanel  firstPanel = new JPanel();

    private void runGUI() {
        myMainWindow.setBounds(10, 10, 400, 400);
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myMainWindow.setLayout(new GridLayout(1,1));
        createFirstPanel();
        myMainWindow.getContentPane().add(firstPanel);
        myMainWindow.setVisible(true);
    }

    private void createFirstPanel() {
        firstPanel.setLayout(new FlowLayout());

        ImageIcon image1 = new ImageIcon("YourImage.ImageFileType");
        Image image2 = image1.getImage().getScaledInstance(300,300,0);
        ImageIcon image3 = new ImageIcon(image2);

        JButton jB = new JButton(image3);
        jB.addActionListener(new TheHandler());
        firstPanel.add(jB);
    }

    private class TheHandler implements ActionListener { //Changed thehandler to TheHandler
        public void actionPerformed(ActionEvent event) { //because it is a class
            //Do Something
        }
    }

    public static void main(String[] args) {
        GUITemplate gt = new GUITemplate();
        gt.runGUI();
    }
}

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

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