简体   繁体   English

如何把可点击的图像jframe

[英]how to put clickable image jframe

我想在jframe中添加图标,在点击按钮时执行某些操作。

You can create a JButton which takes an icon as a parameter and displays it. 您可以创建一个JButton,它将图标作为参数并显示它。 JButton 一个JButton

I highly suggest trying that out first. 我强烈建议先尝试一下。 Hopefully that will help 希望这会有所帮助

You'll probably want to create a JLabel with an Icon and add a MouseListener to the JLabel, like so: 您可能想要创建一个带有Icon的JLabel并将一个MouseListener添加到JLabel,如下所示:

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

public class Foo {
  public static void main(String args[]) {
    // Create a "clickable" image icon.
    ImageIcon icon = new ImageIcon("path/to/image.jpg");
    JLabel label = new JLabel(icon);
    label.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent me) {
        System.out.println("CLICKED");
      }
    });

    // Add it to a frame.
    JFrame frame = new JFrame("My Window");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }
}

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

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