Creating custom JButton from images containing transparent pixels

前端 未结 6 559
悲哀的现实
悲哀的现实 2020-12-02 00:46

Read edit 2 for what I\'m actually missing to make it work

I\'m currently trying to create some custom JButtons using images created in photoshop that have an

6条回答
  •  不思量自难忘°
    2020-12-02 00:52

    If you have a round button, this is exactly what you need:

      public class RoundButton extends JButton {
    
           public RoundButton() {
             this(null, null);
          }
           public RoundButton(Icon icon) {
             this(null, icon);
          }
           public RoundButton(String text) {
             this(text, null);
          }
           public RoundButton(Action a) {
             this();
             setAction(a);
          }
    
           public RoundButton(String text, Icon icon) {
             setModel(new DefaultButtonModel());
             init(text, icon);
             if(icon==null) return;
             setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
             setContentAreaFilled(false);
             setFocusPainted(false);
             initShape();
          }
    
        protected Shape shape, base;
        protected void initShape() {
          if(!getBounds().equals(base)) {
            Dimension s = getPreferredSize();
            base = getBounds();
            shape = new Ellipse2D.Float(0, 0, s.width, s.height);
          }
        }
        @Override public Dimension getPreferredSize() {
          Icon icon = getIcon();
          Insets i = getInsets();
          int iw = Math.max(icon.getIconWidth(), icon.getIconHeight());
          return new Dimension(iw+i.right+i.left, iw+i.top+i.bottom);
        }
    
        @Override public boolean contains(int x, int y) {
          initShape();
          return shape.contains(x, y);
          //or return super.contains(x, y) && ((image.getRGB(x, y) >> 24) & 0xff) > 0;
        }
      }
    

    JButton has a contains() method. Override it and call it on mouseReleased();

提交回复
热议问题