import java.awt.*;
import java.awt.event.*;
class WindTen extends Frame implements ActionListener
{ Panel p;
  ScrollPane scrollpane;
  Button button;
  WindTen()
  { setLayout(new FlowLayout());
p=new Panel();
         button=new Button("one");
scrollpane=new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); 
button.addActionListener(this);
p.add(button);
new Button("two").addActionListener(this);
p.add(new Button("two"));
p.add(new Button("three"));  
p.add(new Button("four"));
scrollpane.add(p);
add(scrollpane);
setBounds(100,100,200,150);
    setVisible(true);
    validate();
    addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e){
            System.exit(0);
        }
    });
  }
  
  
  public void actionPerformed(ActionEvent e)
  { System.exit(0);
  
  }
}
public class ScrollPaneExa { /**
 * @param args
 */
public static void main(String[] args) {
new WindTen();
// TODO Auto-generated method stub }}
上面的程序是把一个panel面板加到滚动面板中,在把四个按钮加到Panel里
         p=new Panel();
         button=new Button("one");
         button.addActionListener(this);
p.add(button);
new Button("two").addActionListener(this);
p.add(new Button("two"));
  为什么button加监听器能退出而 new Button("two")就不能退出??
还有一个问题是关于Cursor类实例化之后,在容器中使用setCursor()方法,最后没有把Cursor对象放到容器中容器也能显示光标形状,而Button之类对象加到容器中才能显示??

解决方案 »

  1.   

    首先LZ要明白new的意义,new就是生成一个新的对象
    new Button("two").addActionListener(this); //这里是一个new的对象添加了监听器
    p.add(new Button("two")); //这里又是另一个new的对象,这个和上面那个是完全不同的两个对象举个例子
    Button a = new Button("a");
    Button b = new Button("a");
    LZ觉得a和b是同一个对象吗?很明显不是,所以你的代码里相当于a添加了监听器,但panel里添加的是b按钮
    所以,b按钮没有添加监听器,所以不会有任何处理