《Java编程思想》读书笔记(5)
今天和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);
}
}
以上是 《Java编程思想》读书笔记(5) 的全部内容, 来源链接: utcz.com/z/390860.html