当前位置: 首页 > 面试题库 >

如何在Java中添加到圆形按钮的金属背景?

尹正奇
2023-03-14
问题内容

如何给这个按钮背景像jbutton
我想给这个按钮金属色或灰色那样怎么做呢?

import java.awt.*;
import java.awt.event.*;

RoundButton-产生轻量级按钮的类。

轻量级组件可以具有“透明”区域,这意味着您可以
在这些区域后面看到容器的背景。

@SuppressWarnings("serial")
public class RoundButton extends Component {

ActionListener actionListener;     // Post action events to listeners
String label;                      // The Button's text
protected boolean pressed = false; // true if the button is detented.


/**
* Constructs a RoundButton with no label.
*/
public RoundButton() {
  this("");
}

/**
* Constructs a RoundButton with the specified label.
* @param label the label of the button
*/
public RoundButton(String label) {
  this.label = label;
  enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}

/**
* gets the label
* @see setLabel
*/
public String getLabel() {
  return label;
}

/**
* sets the label
* @see getLabel
*/
public void setLabel(String label) {
  this.label = label;
  invalidate();
  repaint();
}

/**
* paints the RoundButton
*/
public void paint(Graphics g) {
  int s = Math.min(getSize().width - 1, getSize().height - 1);

  // paint the interior of the button
  if(pressed) {
  g.setColor(getBackground().darker().darker());
  } else {
  g.setColor(getBackground());
  }
  g.fillArc(0, 0, s, s, 0, 360);

  // draw the perimeter of the button
  g.setColor(getBackground().darker().darker().darker());
  g.drawArc(0, 0, s, s, 0, 360);
  // draw the label centered in the button
  Font f = getFont();
  if(f != null) {
  FontMetrics fm = getFontMetrics(getFont());
  g.setColor(getForeground());
  g.drawString(label,
           s/2 - fm.stringWidth(label)/2,
           s/2 + fm.getMaxDescent());
  }
}

/**
* The preferred size of the button. 
*/
public Dimension getPreferredSize() {
  Font f = getFont();
  if(f != null) {
  FontMetrics fm = getFontMetrics(getFont());
  int max = Math.max(fm.stringWidth(label) + 40, fm.getHeight() + 40);
  return new Dimension(max, max);
  } else {
  return new Dimension(100, 100);
  }
}

/**
* The minimum size of the button. 
*/
public Dimension getMinimumSize() {
  return new Dimension(100, 100);
}

/**
* Adds the specified action listener to receive action events
* from this button.
* @param listener the action listener
*/
public void addActionListener(ActionListener listener) {
    actionListener = AWTEventMulticaster.add(actionListener, listener);
    enableEvents(AWTEvent.MOUSE_EVENT_MASK);
 }

 /**
 * Removes the specified action listener so it no longer receives
 * action events from this button.
 * @param listener the action listener
 */
 public void removeActionListener(ActionListener listener) {
     actionListener = AWTEventMulticaster.remove(actionListener, listener);
 }

/**
* Determine if click was inside round button.
*/
 public boolean contains(int x, int y) {
   int mx = getSize().width/2;
   int my = getSize().height/2;
   return (((mx-x)*(mx-x) + (my-y)*(my-y)) <= mx*mx);
}

 /**
 * Paints the button and distribute an action event to all listeners.
   */
 public void processMouseEvent(MouseEvent e) {
   @SuppressWarnings("unused")
Graphics g;
   switch(e.getID()) {
      case MouseEvent.MOUSE_PRESSED:
    // render myself inverted....
    pressed = true;

        // Repaint might flicker a bit. To avoid this, you can use
        // double buffering (see the Gauge example).
    repaint(); 
    break;
      case MouseEvent.MOUSE_RELEASED:
    if(actionListener != null) {
       actionListener.actionPerformed(new ActionEvent(
       this, ActionEvent.ACTION_PERFORMED, label));
    }
    // render myself normal again
    if(pressed == true) {
    pressed = false;

            // Repaint might flicker a bit. To avoid this, you can use
            // double buffering (see the Gauge example).
    repaint();
    }
    break;
      case MouseEvent.MOUSE_ENTERED:

    break;
      case MouseEvent.MOUSE_EXITED:
    if(pressed == true) {
    // Cancel! Don't send action event.
    pressed = false;

            // Repaint might flicker a bit. To avoid this, you can use
            // double buffering (see the Gauge example).
    repaint();

    // Note: for a more complete button implementation,
    // you wouldn't want to cancel at this point, but
    // rather detect when the mouse re-entered, and
    // re-highlight the button. There are a few state
    // issues that that you need to handle, which we leave
    // this an an excercise for the reader (I always
    // wanted to say that!)
    }
    break;
   }
   super.processMouseEvent(e);
}

}

问题答案:

java.awt.Component不支持不透明度/透明度,仅支持Swing组件。

首先要解决的问题是……

* 您应该从轻量级(Swing)组件扩展,因为它们支持透明度
* 无需覆盖`processMouseEvent`,应`MouseListener`改用
* 您的contains方法应考虑按钮的“形状”
* 添加新的侦听器时,应使用内置的事件管理API
* 你应该有利于`paintComponent`在`paint`画轻量级组件时
* 您必须`super.paintXxx`使用任何覆盖的绘画方法进行呼叫,只有极少数的情况您会不这样做,然后您才有责任接管那里的工作
* 您需要通过调用将组件标记为透明 s`etOpaque(false)`



public class TestRoundButton {

    public static void main(String[] args) {
        new TestRoundButton();
    }

    public TestRoundButton() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().setBackground(Color.RED);
                frame.setLayout(new GridBagLayout());
                frame.add(new RoundButton(":)"));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class RoundButton extends JPanel {

        ActionListener actionListener;     // Post action events to listeners
        String label;                      // The Button's text
        protected boolean pressed = false; // true if the button is detented.

        private MouseListener listener;

        /**
         * Constructs a RoundButton with no label.
         */
        public RoundButton() {
            this("");
        }

        @Override
        public void addNotify() {
            super.addNotify();
            if (listener == null) {
                listener = new MouseHandler();
                addMouseListener(listener);
            }
        }

        @Override
        public void removeNotify() {
            removeMouseListener(listener);
            super.removeNotify();
        }

        /**
         * Constructs a RoundButton with the specified label.
         *
         * @param label the label of the button
         */
        public RoundButton(String label) {
            this.label = label;
            //...
            setOpaque(false);
            // Use a mouse listener instead
//            enableEvents(AWTEvent.MOUSE_EVENT_MASK);
        }

        /**
         * gets the label
         *
         * @see setLabel
         */
        public String getLabel() {
            return label;
        }

        /**
         * sets the label
         *
         * @see getLabel
         */
        public void setLabel(String label) {
            this.label = label;
            invalidate();
            repaint();
        }

        /**
         * paints the RoundButton
         */
        // Prefer paintComponent over paint...
        @Override
        protected void paintComponent(Graphics g) {
            // YOU MUST CALL super.paintXxx THERE IS NO EXCUSE NOT TO, EVER!!
            super.paintComponent(g);
            int s = Math.min(getSize().width - 1, getSize().height - 1);

            Graphics2D g2d = (Graphics2D) g.create();
            // paint the interior of the button
            g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

            Color highlight = getBackground();
            if (pressed) {
                highlight = highlight.darker();
            }
            Color darklight = highlight.darker();

            LinearGradientPaint lgp = new LinearGradientPaint(
                    new Point(0, 0),
                    new Point(0, s),
                    new float[]{0, 1f},
                    new Color[]{highlight, darklight});

            Ellipse2D shape = new Ellipse2D.Float(0, 0, s, s);
            g2d.setPaint(lgp);
            g2d.fill(shape);

            // draw the perimeter of the button
            g2d.setColor(getBackground().darker().darker().darker());
            g2d.draw(shape);
            // draw the label centered in the button
            Font f = getFont();
            if (f != null) {
                FontMetrics fm = getFontMetrics(getFont());
                g2d.setColor(getForeground());
                g2d.drawString(label,
                        s / 2 - fm.stringWidth(label) / 2,
                        s / 2 + fm.getMaxDescent());
            }
            g2d.dispose();
        }

        /**
         * The preferred size of the button.
         */
        public Dimension getPreferredSize() {
            Font f = getFont();
            if (f != null) {
                FontMetrics fm = getFontMetrics(getFont());
                int max = Math.max(fm.stringWidth(label) + 40, fm.getHeight() + 40);
                return new Dimension(max, max);
            } else {
                return new Dimension(100, 100);
            }
        }

        /**
         * The minimum size of the button.
         */
        public Dimension getMinimumSize() {
            return new Dimension(100, 100);
        }

        /**
         * Adds the specified action listener to receive action events from this
         * button.
         *
         * @param listener the action listener
         */
        public void addActionListener(ActionListener listener) {
//            actionListener = AWTEventMulticaster.add(actionListener, listener);
//            enableEvents(AWTEvent.MOUSE_EVENT_MASK);
            listenerList.add(ActionListener.class, listener);
        }

        /**
         * Removes the specified action listener so it no longer receives action
         * events from this button.
         *
         * @param listener the action listener
         */
        public void removeActionListener(ActionListener listener) {
//            actionListener = AWTEventMulticaster.remove(actionListener, listener);
            listenerList.add(ActionListener.class, listener);
        }

        /**
         * Determine if click was inside round button.
         */
        public boolean contains(int x, int y) {
            // This needs to work more on the actual painted shape...
            int mx = getSize().width / 2;
            int my = getSize().height / 2;
            return (((mx - x) * (mx - x) + (my - y) * (my - y)) <= mx * mx);
        }
        /**
         * Paints the button and distribute an action event to all listeners.
         */
//        public void processMouseEvent(MouseEvent e) {
//            @SuppressWarnings("unused")
//            Graphics g;
//            switch (e.getID()) {
//                case MouseEvent.MOUSE_PRESSED:
//                    // render myself inverted....
//                    pressed = true;
//
//                    // Repaint might flicker a bit. To avoid this, you can use
//                    // double buffering (see the Gauge example).
//                    repaint();
//                    break;
//                case MouseEvent.MOUSE_RELEASED:
//                    if (actionListener != null) {
//                        actionListener.actionPerformed(new ActionEvent(
//                                this, ActionEvent.ACTION_PERFORMED, label));
//                    }
//                    // render myself normal again
//                    if (pressed == true) {
//                        pressed = false;
//
//                        // Repaint might flicker a bit. To avoid this, you can use
//                        // double buffering (see the Gauge example).
//                        repaint();
//                    }
//                    break;
//                case MouseEvent.MOUSE_ENTERED:
//
//                    break;
//                case MouseEvent.MOUSE_EXITED:
//                    if (pressed == true) {
//                        // Cancel! Don't send action event.
//                        pressed = false;
//
//                        // Repaint might flicker a bit. To avoid this, you can use
//                        // double buffering (see the Gauge example).
//                        repaint();
//
//                        // Note: for a more complete button implementation,
//                        // you wouldn't want to cancel at this point, but
//                        // rather detect when the mouse re-entered, and
//                        // re-highlight the button. There are a few state
//                        // issues that that you need to handle, which we leave
//                        // this an an excercise for the reader (I always
//                        // wanted to say that!)
//                    }
//                    break;
//            }
//            super.processMouseEvent(e);
//        }

        public class MouseHandler extends MouseAdapter {

            @Override
            public void mousePressed(MouseEvent e) {
                pressed = true;
                repaint();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                pressed = false;
                repaint();
            }

        }

    }
}

现在,完成所有这些操作之后,您可能想在 基础组件时认真看一下
javax.swing.AbstractButton



 类似资料:
  • 问题内容: 我想制作一个圆形的大拇指和大拇指向下的按钮。 我应该使用ImageView还是Button作为超类? 我将如何在Swift中做到这一点? 问题答案: 这是一个圆形按钮示例: 斯威夫特3: Swift 2.x:

  • 问题内容: 这可能吗?以下是我尝试过的方法,但它完全用黑色填充了圆圈。 问题答案: SVG元素的图像填充是通过SVG模式实现的。

  • 问题内容: 这可能吗?以下是我尝试过的方法,但它完全用黑色填充了圆圈。 问题答案: SVG元素的图像填充是通过SVG模式实现的。

  • 问题内容: 我只是试图在我的注释点添加一个细节按钮而被卡住,不幸的是,我不知道该怎么做。有人可以帮我吗? 下图显示了我想要实现的目标。谢谢! MapKitViewController: 问题答案: 您做对了,您只需要实现这些方法即可添加按钮以及标题和副标题 iOS 8和Xcode 6 查看我的输出。

  • 我想在Java中添加一个按钮侦听器,这样当用户只需按下按钮时,按钮就会被按下。 我尝试将此操作监听器添加到我创建的按钮: 这就是整个功能: 然而,当我的gui出现时,我在输入输入后按“回车”键,什么也没有发生。我必须亲自点击按钮,这正是我试图避免的! 这是我创建的窗口: 我希望用户输入一个数字,然后按enter键,然后单击按钮。帮助我做错了什么?

  • 问题内容: 我有一个基于Swing的应用程序,其中包含一个。现在,我想使用唯一的行ID来更新或删除每一行。因此,我想向每行添加一个更新和删除按钮,它们具有支持ActionListener的功能。但是,我不知道如何使用NetBeans执行此操作。 问题答案: 要在列中显示按钮,您需要创建: 一个自定义渲染器以显示JButton 定制编辑器以响应鼠标单击 阅读Swing教程中有关如何使用表的部分。关于