简体   繁体   中英

JButton with Icon Clickable Java

Trying to make a jButton with an icon. 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.
  2. Setting the Button's border to 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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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