package Km;import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class ButtonGui implements ActionListener{
JFrame frame;
JButton button;
    JButton button2;
JLabel thisLabel;
JLabel thingLabel;
Box box;
Container container;

    ButtonGui()
{ frame = new JFrame("JUST");
box = Box.createHorizontalBox();
button = new JButton("this测试");
button2 = new JButton("Thing测试");
thisLabel = new JLabel("this no");
thingLabel = new JLabel("thing no");
box.add(button);
box.add(button2);
box.add(thisLabel);
container = frame.getContentPane();
container.add(box);
container.add(thingLabel,BorderLayout.SOUTH);
button.addActionListener(this);
 *************************               button2.addActionListener(new Thing());  **************
frame.setVisible(true);
frame.pack();
}
public void actionPerformed(ActionEvent e) {

if(e.getSource()==button){
thisLabel.setText("this yes");
}
}
public static void main(String []args){
 new ButtonGui(); }}
***************************************************************
package Km;
import java.awt.event.*;public class Thing extends ButtonGui implements ActionListener {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==button2){
thingLabel.setText("Thing yes");
}
}
}****************************************************************
问题就出在 button2.addActionListener(new Thing()); 我想把GUI和事件处理分开,后来发现不得不把时间响应作为GUI的子类
但是还是不行,我的目的只是想知道这种做法为什么不可以!或者说错在哪里,我不想使用内部类,匿名类,或者直接注册到this上
请各位大虾帮忙!

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主【caowy112】截止到2008-06-28 02:01:36的历史汇总数据(不包括此帖):
    发帖数:16                 发帖分:380                
    结贴数:2                  结贴分:40                 
    未结数:14                 未结分:340                
    结贴率:12.50 %            结分率:10.53 %            
      

  2.   

    可以在Thing类中保留ButtonGui的引用.
    如给Thing类提供一个构造方法 public Thing(ButtonGui bg);
    然后声明个成员变量保存这个引用.
    在需要的时候,使用bg来访问ButtonGui类中的方法及成员变量
      

  3.   

    通过Thing构造将button2的引用传进取就可以操作了
      

  4.   

    主类就相当于一个大管家,在这里有着其他一些对象的引用以及成员变量,成员方法...
    因此,在写其他的类的时候,往往会通过一个构造方法来拿到这个大管家的引用.
    ButtonGui bg = null;
    public Thing(ButtonGui bg) {
      super(参数列表);//根据需要?!
      this.bg = bg;
    }
    这是一种常用的方法,因为我们经常会碰到在其他类中需要得到主类中的某个对象或者成员的需求,在这种情况下,我们总不好每次都传该对象的引用,所以,传主类这个大管家的引用进来不失为一种非常好的解决办法.就像拿到private声明的成员变量的getter() and setter()方法,这是一种常用用法.
      

  5.   

    顺便我还想问一下,我用的是public class Thing implements ActionListener来解决的 
    如果我想用public class Thing extends ButtonGui implements ActionListener来做怎么办 ButtonGui bg = null; 
    public Thing(ButtonGui bg) { 
      super(参数列表);//根据需要?! 
      this.bg = bg; 
    } 4楼说的这种在继承中传递的用法我尝试了,但是不行,继续请教!