import java.awt.AWTEvent;
import java.awt.Button;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;public class TestFrame extends Frame{
public TestFrame(){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
public static void main(String[] args) {
MyButton b1 = new MyButton("来抓我啊");
MyButton b2 = new MyButton("我在这里");
b1.SetFriend(b2);
b2.SetFriend(b1);
b2.setVisible(false);
TestFrame tf = new TestFrame();
tf.setTitle("窗口");
tf.setSize(400, 300);
tf.add(b1,"North");
tf.add(b2,"South");
tf.setVisible(true);
}
}
class MyButton extends Button{
private MyButton friend;
public void SetFriend(MyButton friend){
this.friend = friend;
} public MyButton(String label) throws HeadlessException {
super(label);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
} protected void processMouseMotionEvent(MouseEvent e) {
setVisible(false);
friend.setVisible(true);
}
}
运行后下面的那个按钮第一次会消失不见 必须最大化才可以看到。
有什么办法修复没?

解决方案 »

  1.   

    public static void main(String[] args) {
            MyButton b1 = new MyButton("来抓我啊");
            MyButton b2 = new MyButton("我在这里");
            b1.SetFriend(b2);
            b2.SetFriend(b1);
            b2.setVisible(true);//把这句里的false改成true就好了  这样就能实现自动隐藏了
            Replace tf = new Replace();
            tf.setTitle("窗口");
            tf.setSize(400, 300);
            tf.add(b1,"North");
            tf.add(b2,"South");
            tf.setVisible(true);
        }
      

  2.   

    button.setBounds(x,y,width,height) 就固定了
      

  3.   


    你大概没看懂意思。他的意思是一出来就显示button1,隐藏button2。
    然后mouse在哪个上面就隐藏哪个,同时显示另外一个。
    我试了,确实很奇怪。
    更恶心的是,resize以后,button的宽度都变得不一样了。我弄了半天也不懂。
    要是用JFrame的话,应该就好弄了。
      

  4.   


    6#的方法我试过
    如下     tf.add(b1,"North");
            tf.add(b2,"South");
            b1.setBounds(10, 35, 20, 30);
            b2.setBounds(10, 265, 20, 30);
    但是在鼠标点b1不能完全显示b2
      

  5.   

    public static void main(String[] args) {
    MyButton b1 = new MyButton("来抓我啊");
    MyButton b2 = new MyButton("我在这里");
    b1.SetFriend(b2);
    b2.SetFriend(b1);
    TestFrame tf = new TestFrame();
    tf.setTitle("窗口");
    tf.setSize(400, 300);
    tf.add(b1, "North");
    tf.add(b2, "South");
    tf.setVisible(true);
    b2.setVisible(false);
    }
    b2.setVisible(false);这句话放在构造方法最下面,swing程序里显示不正常很多的时候都是setVisible方法调用的时机有问题造成的,改成这样就可以了