繁体   English   中英

带有图标可点击 Java 的 JButton

[英]JButton with Icon Clickable Java

试图制作一个带有图标的 jButton。 如何摆脱图标后面的按钮轮廓以及如何使图标可点击? 我的动作侦听器被激活的唯一方法是单击图标后面的按钮轮廓。 不是实际的图标。

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 的内部灰色方块是图标,不可点击,白色部分是唯一“可点击”的部分

试试这个例子。

关键语句是更改按钮大小以匹配图标。 因此,您可能希望将图标缩放到适当的大小。

其他选择是:

  1. 使用 setMargins 将 Button 的 insets 更改为全 0。
  2. 将 Button 的边框设置为null 这并不表示该按钮已被按下。

我更喜欢调整大小或插入选项。

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