Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9135087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:46:45+00:00 2026-06-17T08:46:45+00:00

I found 2 different solutions that don’t work for me. The first one deals

  • 0

I found 2 different solutions that don’t work for me. The first one deals with transparency. The second one I would prefer because it’s cleaner looking. The goal is to create custom shaped buttons using images that have transparency. I want to ignore the transparent sections and only take action when I click on the non-transparent part of the image.

First code comes from here http://java.macteki.com/2012/07/custom-shape-buttons.html. By the way, what is the point of 0x00ffffff in the code below?

//********** BEGIN OF IMAGE BUTTON CODE ****************
      // The following is the actual code to create a image button
      // you may use any transparent image file, just change "a.png" below
      final BufferedImage image = ImageIO.read(new File("a.png"));
      ImageIcon icon = new ImageIcon(image);

      jLabel1 = new javax.swing.JLabel(icon);
      jLabel1.addMouseListener(new MouseAdapter()
      {
      public void mouseClicked(MouseEvent e)
      {
      boolean transparent = (image.getRGB(e.getX(),e.getY()) & 0x00ffffff)!=0;
     if (!transparent) {
      // write your button handler here
       System.out.println("button pressed");
      } else {
        System.out.println("else");
      }
      }
      }

      );
      //********** END OF IMAGE BUTTON CODE ****************
      // add the button to the panel so that it becomes visible

It works with his test image, but does not work with any of mine. I even took his and just changed the color of the A in gimp, exported to a2.png and it does not work. It registers all areas as else and if (!transparent) never triggers.

This image works:
This image works
This image does not work:
This image does not work

The second code that I would prefer comes from here Creating a custom button in Java with JButton. The image applies to the button, but a click anywhere in the box, including the transparent areas will register as a click. I want it to only work when you click on the non-transparent areas (or the A in this example).

BufferedImage startButton = ImageIO.read(new File("a2.png"));       
        jButton1 = new javax.swing.JButton(new ImageIcon(startButton));  
        jButton1.setBorder(BorderFactory.createEmptyBorder());
        jButton1.setContentAreaFilled(false);
        jButton1.setFocusable(false);

Here is the code I am trying to use based on the example from Guillame

private void initComponents() throws IOException {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        final BufferedImage image = ImageIO.read(getClass().getResource("/images/a.png"));
        jButton1 = new JButton(new ImageIcon(image)) {
             @Override
             public boolean contains(int x, int y) {
                 Rectangle viewRect = getBounds();
                 Insets insets = getInsets();
                 viewRect.x += insets.left;
                 viewRect.y += insets.top;
                 viewRect.width -= insets.left + insets.right;
                 viewRect.height -= insets.top + insets.bottom;
                 Rectangle iconR = new Rectangle();
                 SwingUtilities.layoutCompoundLabel(this, this.getFontMetrics(this.getFont()), this.getText(), this.getIcon(),
                         this.getVerticalAlignment(), this.getHorizontalAlignment(), this.getVerticalTextPosition(),
                         this.getHorizontalTextPosition(), viewRect, iconR, new Rectangle(), this.getIconTextGap());
                 if (!iconR.contains(x, y)) {
                     return false;
                 }
                 x -= iconR.x;
                 y -= iconR.y;
                 Color c = new Color(image.getRGB(x, y), true);
                 return c.getAlpha() != 0 && (c.getRed() < 255 || c.getGreen() < 255 || c.getBlue() < 255);
             }
         };

        jButton1.setContentAreaFilled(false); 
        jButton1.setFocusPainted(false);            
        jButton1.setRolloverEnabled(false);       
        jButton1.setBorderPainted(false);

        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(72, 72, 72)
                .addComponent(jButton1)
                .addContainerGap(255, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(193, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(84, 84, 84))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:46:46+00:00Added an answer on June 17, 2026 at 8:46 am

    You need to override the method contains(int,int) of JButton for your second method to work. Now the hard part is to figure out if you are on a relevant part of the image or not.
    In this case I made the assumption that fully transparent pixels are not relevant and that white pixels are not relevant either. Up to you to choose a different implementation:

    import java.awt.Color;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.SwingUtilities;
    
    public class TestTransparentButton {
    
        protected void createAndShowGUI() throws MalformedURLException, IOException {
            JFrame frame = new JFrame("Test button");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final BufferedImage image = ImageIO.read(new URL("https://i.stack.imgur.com/7D547.png"));
            final JButton button = new JButton(new ImageIcon(image)) {
                @Override
                public boolean contains(int x, int y) {
                    Rectangle viewRect = getBounds();
                    Insets insets = getInsets();
                    viewRect.x = insets.left;
                    viewRect.y = insets.top;
                    viewRect.width -= insets.left + insets.right;
                    viewRect.height -= insets.top + insets.bottom;
                    Rectangle iconR = new Rectangle();
                    SwingUtilities.layoutCompoundLabel(this, this.getFontMetrics(this.getFont()), this.getText(), this.getIcon(),
                            this.getVerticalAlignment(), this.getHorizontalAlignment(), this.getVerticalTextPosition(),
                            this.getHorizontalTextPosition(), viewRect, iconR, new Rectangle(), this.getIconTextGap());
                    if (!iconR.contains(x, y)) {
                        return false;
                    }
                    x -= iconR.x;
                    y -= iconR.y;
                    Color c = new Color(image.getRGB(x, y), true);
                    return c.getAlpha() != 0 && (c.getRed() < 255 || c.getGreen() < 255 || c.getBlue() < 255);
                }
            };
            button.setContentAreaFilled(false);
            button.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(button, "You clicked on the button");
                }
            });
            frame.add(button);
            frame.setSize(200, 200);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new TestTransparentButton().createAndShowGUI();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
    
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have tried a variety of different solutions found on stack and other places
I found different Stackoverflow-Questons, but I don't see what I'm doing wrong in my
I have found two different things in two well known books in c, first
While googling I found two different sets of headers that need to be set
I found there're two different opinions about how greedy regex is executed: one is,
I found out that I can use a different theme in an C# WPF
I have searched and found a lot of different things but none that actually
I've found a feature on two different websites that I'd like to include on
I found that jQuery :odd selector and CSS3 nth-child(odd) works different. http://jsfiddle.net/TMDwT/5/ In yellow
I have found a whole lot of different solutions to this problem, but not

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.