designjava中的例子,关于装饰pattern,问题写在程序后面的注释里面了。
另外请高手讲一下这几个类的关系,我有点似懂非懂的。
import javax.swing.*;
import javax.swing.JComponent;
import java.awt.*;
class Decorator extends JComponent {

public Decorator(JComponent c) {
setLayout(new BorderLayout());
//add component to container
add("Center", c);
}
}
import javax.swing.*;
import javax.swing.JComponent;
import java.awt.*;
public class SlashDecorator extends Decorator
{
int x1, y1, w1, h1; //saved size and posn
public SlashDecorator(JComponent c) {
super(c);
}
//----------------------------------------------
public void setBounds(int x, int y, int w, int h) {//搞不懂这里这个方法什么时候调用的?参数从哪里传来的?
x1 = x; y1= y; //save coordinates
w1 = w; h1 = h;
super.setBounds(x, y, w, h);
}
//----------------------------------------------
public void paint(Graphics g) {
super.paint(g); //draw button
g.setColor(Color.red); //set color
g.drawLine(0, 0, w1, h1); //draw red line
}
}import javax.swing.*;
import javax.swing.JComponent;
import java.awt.*;
import java.awt.event.*;
public class useCoolDecorator extends JFrame
{
public useCoolDecorator(){
super("useCoolDecorator");
JPanel jp=new JPanel();
getContentPane().add(jp);
//jp.add(new CoolDecorator(new JButton("cool button")));
jp.add(new SlashDecorator(new JButton("cool button")));
setSize(500,500);
setVisible(true);
}
public static void main(String[] arg)
{
new useCoolDecorator();
}
}

解决方案 »

  1.   

    这个关系应当不是很复杂把Decorator继承JComponent,SlashDecorator继承Decorator.
    最后的useCoolDecorator 只是一个表现作用的类,其中用到了Decorator,SlashDecorator得对象你注释的那块,是对JComponent中的方法的覆盖,以便增强JComponent中setBorder的功能已达到己用
    在你的代码里面没有对覆盖后的方法的调用,但是由于继承了其父类(也就是JComponent)中的所有方法,是会有继承下来的方法调用这个覆盖后的setBorder方法的比如:reshape(int x, int y, int w, int h)等明白?
      

  2.   

    public void setBounds(int x, int y, int w, int h) {//搞不懂这里这个方法什么时候调用的?参数从哪里传来的?
    这个方法是从父类继承过来的,在Java绘制图形界面时调用,比如说:JFrame frame = new JFrame();            //生成新实例
    frame.setBounds(100, 100, 100, 100);    //设定边界
    frame.setVisible(true);                 //显示组件