public class Fonts2Panel extends JPanel {   
 public void paintComponent(Graphics g) {
   String myquote="Happiness is an attitude.";
   Font f=new Font("Times New Roman",Font.BOLD+Font.ITALIC,24);
   g.setFont(f);
   FontMetrics fm=getFontMetrics(f); 
   int x=(getSize().width - fm.stringWidth(myquote))/2;
   int y=getSize().height/2;
   g.drawString(myquote,x,y);
 }
 public static void main(String args[]){
     Fonts2Panel fo=new Fonts2Panel();
     fo.setVisible(true);
 }
}     帮忙看看这段代码,怎么结果显示不出来?哪错了????

解决方案 »

  1.   

    JFrame f=new JFrame();
    f.getContextPane().add(fo);
    f.show();
      

  2.   

    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;import javax.swing.*;
    public class Fonts2Panel extends JPanel {   
     public void paintComponent(Graphics g) {
         String myquote="Happiness is an attitude.";
       Font f=new Font("Times New Roman",Font.BOLD+Font.ITALIC,24);
       g.setFont(f);
       FontMetrics fm=getFontMetrics(f); 
       int x=(getSize().width - fm.stringWidth(myquote))/2;
       int y=getSize().height/2;
       g.drawString(myquote,x,y);
     }
     public static void main(String args[]){
         Fonts2Panel fo=new Fonts2Panel();
         fo.setVisible(true);
         JFrame ff=new JFrame();
         ff.getContentPane().add(fo);
                  ff.setSize(500,500);
         ff.setVisible(true);
         
     }
      

  3.   

    fo.setVisible(true);这句不要,多余的
    忘删了
      

  4.   

    谢谢了,知道了,就是说main方法里要定义一个 Fonts2Panel 类的对象,然后将这个对象在加到JFrame的一个对象框架中,在定义内容窗格的大小就好了!!
      

  5.   

    是的,就是这道理,JPane不能独立显示,要先加载到比如JFrame里才能显示