利用Graphics类做的一些习题(二)

题目

**15.2 (创建一个自定制的按钮类)扩展JButton类,开发一个名为OvalButton的自定制按钮类,将按钮上的文本显示在椭圆中。

效果

在这里插入图片描述

代码:

package Test;

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

public class Exercise15_2 extends JFrame {
    public Exercise15_2(){
        setTitle("OvalButton");
        setLayout(new GridLayout(1,2,5,5));
        add(new OvalButton());
        add(new OvalButton2());

    }

    public static void main(String[] args) {
        Exercise15_2 frame=new Exercise15_2();
        frame.setTitle("OvalButton");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
class OvalButton extends JButton{

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(10,10,getWidth()-20,getHeight()-20);
        FontMetrics fm=g.getFontMetrics();
            int stringWidth=fm.stringWidth("OK");
            int stringAscent=fm.getAscent();

            int xCoordinate=getWidth()/2-stringWidth/2;
            int yCoordinate=getHeight()/2+stringAscent/2;
            g.drawString("OK",xCoordinate,yCoordinate);


    }
}

class OvalButton2 extends JButton{

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(10,10,getWidth()-20,getHeight()-20);
        FontMetrics fm=g.getFontMetrics();
        int stringWidth=fm.stringWidth("Cancel");
        int stringAscent=fm.getAscent();

        int xCoordinate=getWidth()/2-stringWidth/2;
        int yCoordinate=getHeight()/2+stringAscent/2;
        g.drawString("Cancel",xCoordinate,yCoordinate);


    }
}

思路分析

因为paintComponent每次都会被JVM自动调用数次,无论是鼠标单击还是页面切换的时候都会调用若干次,所以paintComponent的复用就显得困难,故定义两个类,都继承自JButton,重写paintComponent方法以供使用。

		FontMetrics fm=g.getFontMetrics();
        int stringWidth=fm.stringWidth("OK");
        int stringAscent=fm.getAscent();

        int xCoordinate=getWidth()/2-stringWidth/2;
        int yCoordinate=getHeight()/2+stringAscent/2;
        g.drawString("OK",xCoordinate,yCoordinate);
        
        int xCoordinate=getWidth()/2-stringWidth/2;
        int yCoordinate=getHeight()/2+stringAscent/2;
        g.drawString("Cancel",xCoordinate,yCoordinate);

上述代码是利用绘制字符串的方法,设定了文本内容,文本居中,即框架的长度和高度都除以二。

    g.drawOval(10,10,getWidth()-20,getHeight()-20);

表示椭圆从坐标点(10,10)开始绘制,大小是整体框架大小-20,这样不会占据整个框架导致溢出又可以很好的居中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值