简体   繁体   English

带有图标可点击 Java 的 JButton

[英]JButton with Icon Clickable Java

Trying to make a jButton with an icon.试图制作一个带有图标的 jButton。 How do I get rid of the button outline behind the icon and how do i make the icon clickable?如何摆脱图标后面的按钮轮廓以及如何使图标可点击? The only way my action Listener is being activated is if the button outline behind the icon is clicked.我的动作侦听器被激活的唯一方法是单击图标后面的按钮轮廓。 Not the actual icon.不是实际的图标。

public class RoundButton extends JButton {
    String iconPath = "/Users/Desktop/SNN/snn_emro_ui/gui_emro/gui_emro copy/src/resources/cross.png";
    JButton exitButton;
    public RoundButton() {
        ImageIcon icon = new ImageIcon(iconPath);
        exitButton = new JButton(icon);
        add(exitButton);
    }
}

带有 X 的内部灰色方块是图标,不可点击,白色部分是唯一“可点击”的部分

Try this example.试试这个例子。

The key statement is changing the button size to match the Icon.关键语句是更改按钮大小以匹配图标。 So you may want to scale the Icon to an appropriate size.因此,您可能希望将图标缩放到适当的大小。

Other options are to:其他选择是:

  1. Change the insets of the Button to all 0's using setMargins.使用 setMargins 将 Button 的 insets 更改为全 0。
  2. Setting the Button's border to null .将 Button 的边框设置为null This doesn't give any indication that the button has been pressed.这并不表示该按钮已被按下。

I prefer the resizing or insets option.我更喜欢调整大小或插入选项。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JButtonExample extends JPanel {

    final static int height = 500;
    final static int width = 500;
    JFrame frame = new JFrame();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JButtonExample().start());
    }

    public void start() {
        File file = new File("your image file name here");
        try {
        Image img = ImageIO.read(file);
        ImageIcon icon = new ImageIcon(img);
        JButton button = new JButton(icon);
        add(button);
        setBackground(Color.white);
        button.addActionListener((ae)-> System.out.println("Button Clicked"));
        button.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }

    public JButtonExample() {
        frame.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        setPreferredSize(
                new Dimension(width, height));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}

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

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