且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

《Java编程思想》读书笔记(5)

更新时间:2022-09-16 16:27:04

今天和vandalor讨论到多态的思想和好处,自己对多态也有了进一步的认识。再来想了想前面一篇笔记中的代码,想到如果用户能够在不知道到底是applet还是窗体的情况能够跑起来的话,那应该更符合封装的思想了。所得代码如下:

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

public class Console 
{
    public static String title(Object obj)
    {
        String str = "";
        str = obj.getClass().toString();
        if(str.indexOf("class")!=-1)
        {
            str = str.substring(6);
        }
        return str;
    }
    public static void run(JFrame frame,int width,int height)
    {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle(title(frame));
        frame.setSize(width,height);
        frame.setVisible(true);
    }
    
    public static void run(JApplet applet,int width,int height)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle(title(applet));
        frame.setSize(width,height);
        frame.getContentPane().add(applet);
        applet.init();
        applet.start();
        frame.setVisible(true);
    }
    
    public static void run(JPanel panel,int width,int height)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle(title(panel));
        frame.setSize(width,height);
        frame.getContentPane().add(panel);
        frame.setVisible(true);

    }

}
        

//Test.java
import javax.swing.*;

public class Test extends JApplet
{

    /**
     * @param args
     */
    public void init()
    {
        JLabel lb1 = new JLabel("Hello,World");
        this.getContentPane().add(lb1);
    }
    public static void main(String[] args)
    {
        Test t1 = new Test();
        Console.run(t1,300,300);

    }

}




本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2006/06/01/414397.html,如需转载请自行联系原作者