roundbutton.java~23~

来自「Contains a complete archiver by Haruhiko」· JAVA~23~ 代码 · 共 68 行

JAVA~23~
68
字号
package swingexample;

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class RoundButton extends JButton {
  public RoundButton(String strName) {
    super(strName);

    // 声明椭圆按钮的长轴和短轴的大小。
    Dimension size = getPreferredSize();
    size.height = Math.max(size.width, size.height);
    size.width = size.height + (size.height / 2);
    setPreferredSize(size);

    //使JButton不画背景,而画一个椭圆背景。
    setContentAreaFilled(false);
  }

  protected void paintComponent(Graphics g) {
    if (getModel().isArmed()) {

      // 你可以选一个高亮的颜色作为圆形按钮类的属性
      g.setColor(Color.red);
    }
    else {
      g.setColor(getBackground());
    }
    g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);

    super.paintComponent(g);
  }

  // 用简单的弧画按钮的边界。
  protected void paintBorder(Graphics g) {
    g.setColor(getForeground());
    g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
  }

  // 侦测点击事件
  Shape shape;
  public boolean contains(int x, int y) {

    // 如果按钮改变大小,产生一个新的形状对象。
    if ((shape == null)
        ||(!shape.getBounds().equals(getBounds()))) {
      shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
    }
    return shape.contains(x, y);
  }

  // 测试程序
  public static void main(String[] args) {
    // 产生一个带‘Jackpot’标签的按钮。
    JButton button = new RoundButton("Jackpot");
    button.setBackground(Color.green);

    // 产生一个框架以显示这个按钮。
    JFrame frame = new JFrame();
    frame.getContentPane().setBackground(Color.yellow);
    frame.getContentPane().add(button);
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setSize(150, 150);
    frame.setVisible(true);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?