⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ellipsebutton.java

📁 一个Java Swing的按钮例子
💻 JAVA
字号:
// package swingexample;

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

public class EllipseButton
    extends JButton {
  private Shape shape;

  public EllipseButton(String strName) {
    super(strName);

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

	    //  添加事件处理器
    ActionListener al = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "内容", "标题", JOptionPane.INFORMATION_MESSAGE);
      }
    };

    addActionListener(al);

    // 使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);
  }

  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[] agrs) {
    JButton button = new EllipseButton("椭圆按钮");
    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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -