创建一个圆形的按钮
来源:互联网 发布:淘宝的组装电脑靠谱吗 编辑:程序博客网 时间:2024/05/06 14:20
<script type="text/javascript">google_ad_client = "pub-8800625213955058";/* 336x280, 创建于 07-11-21 */google_ad_slot = "0989131976";google_ad_width = 336;google_ad_height = 280;//</script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>创建一个圆形的按钮作者:jackliue-mail:suntoday@eyou.com这个主题是关于一个圆形的Swing按钮,实际上,这个技巧可以适用于制作任何形状的按钮,我们将实现一个圆形轮廓的按钮。当去创建一个圆形按钮时有两件事情去做,第一是为了画出一个圆形轮廓而重新实现原来的轮廓实现方法,第二是建立一些动作以便在你当你点击在里面的圆形按钮时有应答反应。这是一个样例程序,它扩展了JButton
import java.awt.*;import java.awt.geom.*;import javax.swing.*;import java.awt.event.*;public class RoundButton extends JButton { public RoundButton(String label) { super(label); //下面的语句讲述这个按钮变为一个圆形而不是椭圆形 Dimension size = getPreferredSize(); size.width = size.height = Math.max(size.width, size.height); setPreferredSize(size); //不让JButton画背景而允许我们去画一个圆背景 setContentAreaFilled(false); } // 画出圆的背景和标签 protected void paintComponent(Graphics g) { if (getModel().isArmed()) { g.setColor(Color.lightGray); } 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) { // 如果按钮改变了尺寸将重新创建一个Shape 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) { JButton button1 = new RoundButton("http://www.77750.com"); JButton button2 = new RoundButton("欢迎你常来做客"); button1.setBackground(Color.green); button2.setBackground(Color.yellow); // 创建一个Fram来显示这个按钮 JFrame frame = new JFrame(); frame.getContentPane().add(button1); frame.getContentPane().add(button2); frame.getContentPane().setLayout(new FlowLayout()); frame.setSize(450, 350); frame.setVisible(true); //测试单击事件 button1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("you click button1!"); } }); button2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("you click button2!"); } }); }}
这个RoundButton类扩展了JButton类,因为我们想要保持大多数JButton的特性。在这个RoundButton构造函数中,方法setContentAreaFilled()被调用,它给按钮产生一个长方形焦点,但是没有画出背景。现在我们需要画出圆的背景。它覆盖了paintComponent()方法,这个方法使用了一个Graphics对象的fillOval()方法画出一个填充的圆形。然后调用超类的paintComponent()方法,paintComponent()在填充圆里画出一个标签。为了画出一个圆形按钮的周围边框,这个例子也覆盖了paintBorder()方法,如果你不需要一个边框,可以不覆盖这个方法。这个方法调用一个Graphics对象的fillOval()方法来画出一个圆的细边框。最后,我们需要在当用户单击它时有一个响应,但当超出边界时则没有响应。按缺省情况,一个JButton对于一个长方形按钮区域的反应良好,但JButton对于按钮没有的真正意义上的形状观念,因此它仅仅假定了按钮是一个长方形的。告诉JButton一个真实的形状需要你去覆盖contains()方法。contains()方法获得一个坐标值,并且如果坐标值包含在按钮里面便返回true,否则就返回false。运行结果图如下:打包下载原代码