一个小测试,MessagePanel继承于Panel,显示结果为:
1 import java.awt.*; 2 3 import javax.swing.*; 4 5 public class hello extends JFrame{ 6 public hello(){ 7 MessagePanel mp1=new MessagePanel("Welcome to Java"); 8 MessagePanel mp2=new MessagePanel("Java is fun"); 9 MessagePanel mp3=new MessagePanel("Java is cool"); 10 MessagePanel mp4=new MessagePanel("I love Java"); 11 12 mp1.setFont(new Font("SansSerif",Font.ITALIC,20)); 13 mp2.setFont(new Font("Courier",Font.BOLD,20)); 14 mp3.setFont(new Font("Times",Font.ITALIC,20)); 15 mp4.setFont(new Font("Californian FB",Font.PLAIN,20)); 16 17 mp1.setBackground(Color.red); 18 mp2.setBackground(Color.cyan); 19 mp3.setBackground(Color.green); 20 mp4.setBackground(Color.white); 21 mp1.setCentered(true); 22 23 setLayout(new GridLayout(2,2)); 24 add(mp1); 25 add(mp2); 26 add(mp3); 27 add(mp4); 28 } 29 30 public static void main(String[] args){ 31 hello frame=new hello(); 32 frame.setSize(300,200); 33 frame.setTitle("Test MessagePanel"); 34 frame.setLocationRelativeTo(null); 35 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 36 frame.setVisible(true); 37 } 38 } 39 40 41 class MessagePanel extends JPanel{ 42 private String message="Welcome to Java"; 43 private int xCoordinate=20; 44 private int yCoordinate=20; 45 private boolean centered; 46 private int interval=10; 47 public MessagePanel(){} 48 public MessagePanel(String message){ 49 this.message=message; 50 } 51 public String getMessage(){ 52 return message; 53 } 54 public void getMessage(String message){ 55 this.message=message; 56 } 57 public int getXCoordinate(){ 58 return xCoordinate; 59 } 60 public void setXCoordinate(int x){ 61 this.xCoordinate=x; 62 repaint(); 63 } 64 public int getYCoordinate(){ 65 return yCoordinate; 66 } 67 public void setYCoordinate(int y){ 68 this.yCoordinate=y; 69 repaint(); 70 } 71 public boolean isCentered(){ 72 return centered; 73 } 74 public void setCentered(boolean centered){ 75 this.centered=centered; 76 repaint(); 77 } 78 79 public int getInterval(){ 80 return interval; 81 } 82 83 public void setinterVal(int interval){ 84 this.interval=interval; 85 repaint(); 86 } 87 protected void paintComponent(Graphics g){ 88 super.paintComponent(g); 89 if(centered){ 90 FontMetrics fm = g.getFontMetrics(); 91 int stringWidth=fm.stringWidth(message); 92 int stringAscent=fm.getAscent(); 93 xCoordinate=getWidth()/2-stringWidth/2; 94 yCoordinate=getHeight()/2-stringAscent/2; 95 } 96 g.drawString(message, xCoordinate, yCoordinate); 97 } 98 public void moveLeft(){ 99 xCoordinate-=interval; 100 repaint(); 101 } 102 public void moveRight(){ 103 xCoordinate+=interval; 104 repaint(); 105 } 106 107 public void moveUp(){ 108 yCoordinate-=interval; 109 repaint(); 110 } 111 public void moveDown(){ 112 yCoordinate+=interval; 113 repaint(); 114 } 115 public Dimension getPreferredSize(){ 116 return new Dimension(200,30); 117 } 118 119 }