今天和vandalor讨论到多态的思想和好处,自己对多态也有了进一步的认识。再来想了想前面一篇笔记中的代码,想到如果用户能够在不知道到底是applet还是窗体的情况能够
跑起来的话,那应该更符合封装的思想了。所得代码如下:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> //Console.java
importjava.awt.*;
importjavax.swing.*;
publicclassConsole
{
publicstaticStringtitle(Objectobj)
{
Stringstr="";
str=obj.getClass().toString();
if(str.indexOf("class")!=-1)
{
str=str.substring(6);
}
returnstr;
}
publicstaticvoidrun(JFrameframe,intwidth,intheight)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(frame));
frame.setSize(width,height);
frame.setVisible(true);
}
publicstaticvoidrun(JAppletapplet,intwidth,intheight)
{
JFrameframe=newJFrame();
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);
}
publicstaticvoidrun(JPanelpanel,intwidth,intheight)
{
JFrameframe=newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(panel));
frame.setSize(width,height);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
importjava.awt.*;
importjavax.swing.*;
publicclassConsole
{
publicstaticStringtitle(Objectobj)
{
Stringstr="";
str=obj.getClass().toString();
if(str.indexOf("class")!=-1)
{
str=str.substring(6);
}
returnstr;
}
publicstaticvoidrun(JFrameframe,intwidth,intheight)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(frame));
frame.setSize(width,height);
frame.setVisible(true);
}
publicstaticvoidrun(JAppletapplet,intwidth,intheight)
{
JFrameframe=newJFrame();
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);
}
publicstaticvoidrun(JPanelpanel,intwidth,intheight)
{
JFrameframe=newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(panel));
frame.setSize(width,height);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
//Test.java
importjavax.swing.*;
publicclassTestextendsJApplet
{
/**
*@paramargs
*/
publicvoidinit()
{
JLabellb1=newJLabel("Hello,World");
this.getContentPane().add(lb1);
}
publicstaticvoidmain(String[]args)
{
Testt1=newTest();
Console.run(t1,300,300);
}
}
//Test.java
importjavax.swing.*;
publicclassTestextendsJApplet
{
/**
*@paramargs
*/
publicvoidinit()
{
JLabellb1=newJLabel("Hello,World");
this.getContentPane().add(lb1);
}
publicstaticvoidmain(String[]args)
{
Testt1=newTest();
Console.run(t1,300,300);
}
}