题目
**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,这样不会占据整个框架导致溢出又可以很好的居中。