簡體   English   中英

使用Java GUI將事件處理程序插入圖像

[英]Inserting event handler into images using Java GUI

我想插入圖像,然后使用Java GUI向該圖像添加事件。 我添加圖像,然后嘗試將其插入此容器,但顯示錯誤。 您能告訴我哪種方法是在Java中插入圖像,然后向該圖像或事件處理程序添加偵聽器的正確方法嗎? 或者如果使用容器來處理圖像是正確的方法。 我該怎么做?

這是我的代碼:

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

這是使用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