Java: using an image as a button

徘徊边缘 提交于 2019-11-27 03:42:37
jzd

Remove the border like so:

button.setBorder(BorderFactory.createEmptyBorder());

and then also the contents1:

button.setContentAreaFilled(false);

1: Taken from the solution added to the question by @3sdmx

thotheolh

A suggestion would be to set the Image as a label and add a mouse listener to the label to detect clicks.

Example:

ImageIcon icon = ...;

JLabel button = new JLabel(icon);

button.addMouseListener(new MouseAdapter() {
  @Override
  public void mouseClicked(MouseEvent e) {
     ... handle the click ...
  }
});

buttonIcon.setBorder(new EmptyBorder(0,0,0,0));

button.setBorderPainted( false );

This can be done easily in netbeans by setting the contentAreaFilled Property to False

    BufferedImage buttonIcon = ImageIO.read(new File("myImage.png"));
    button = new JButton(new ImageIcon(buttonIcon));
    button.setBorderPainted(false);
    button.setFocusPainted(false);
    button.setContentAreaFilled(false);

just write this

button.setContentAreaFilled(false);

As far i know, there is no easy way of doing it, you will need to override the "paintComponent" method of the JButton class to aint your image, if you only want to display an image and behave like a button, you can add a JPanel wich draws the image (clicky) and add a MouseListener/MouseAdapter to handle the "mousePressed" event

I followed below steps and i could create an 'ImageButton' successfully.

  1. Create a JButton
  2. Added an action listener
  3. Set an image icon (note i have placed the info.png icon in the src\main\resources folder and loaded using class loader). The project structure is as here.

  4. Set an empty Border
  5. Disabled the content area filling
  6. Disabled the focusability
  7. Added to the contentPane

PFB the code that worked for me

JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Info clicked");
    }
});

String iconfilePath = this.getClass().getClassLoader().getResource("info.png").getFile();
btnNewButton.setIcon(new ImageIcon(iconfilePath));
btnNewButton.setBounds(10, 438, 39, 31);
btnNewButton.setBorder(BorderFactory.createEmptyBorder());
btnNewButton.setContentAreaFilled(false);
btnNewButton.setFocusable(false);
contentPane.add(btnNewButton);

The output button resulted from above code is as below

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!