请问为啥变量 r 没能获取组件的Bounds呢?
还有为啥没写JFrame的setDefaultCloseOperation(EXIT_ON_CLOSE)语句的情况下可以点击“X”关闭界面呢?
代码:
import java.awt.Rectangle;
import javax.swing.JFrame;public class Hello extends JFrame{
    public Hello(String name){
     Rectangle r=new Rectangle();
     r=getBounds(r);
     System.out.println("X ="+r.x);
     System.out.println("Y ="+r.y);
     System.out.println("Width ="+r.width);
     System.out.println("Height ="+r.height);  
    }

    public static void main(String[] args) {
Hello frame=new Hello("test");
frame.setBounds(20, 50, 100, 200);
frame.setVisible(true); }}结果:X =0
Y =0
Width =0
Height =0

解决方案 »

  1.   

    没搞过swing 不过Hello frame=new Hello("test");
    frame.setBounds(20, 50, 100, 200);你取值的时候是不是还没赋值啊?是不是默认的情况下"X"是关闭?
      

  2.   

    请问为啥变量 r 没能获取组件的Bounds呢?
    你new的Rectangle初始值就是0,0,0,0。参考类的第一个构造方法的说明:Constructs a new Rectangle whose upper-left corner is at (0, 0) in the coordinate space, and whose width and height are both zero.还有为啥没写JFrame的setDefaultCloseOperation(EXIT_ON_CLOSE)语句的情况下可以点击“X”关闭界面呢?
    Swing的JFrame默认点击关闭时是会直接隐藏窗口的。参考JFrame说明:a JFrame has some notion of how to respond when the user attempts to close the window. The default behavior is to simply hide the JFrame when the user closes the window. To change the default behavior, you invoke the method setDefaultCloseOperation(int). To make the JFrame behave the same as a Frame instance, use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).
      

  3.   

    主要是对Rectangle对象值的传递不是很明白哦,但是
    new 的时候直接初始化, Rectangle r=new Rectangle(10,10,50,50);试过了 还是0 0 0 0啊.
    为什么呢?还有 我关闭窗口时 不是hide了起来,而是直接把窗口关了啊!
    这又是怎么回事呢?
    我在eclipse3.5和EditPlus3.0里运行的都得了这样的结果
      

  4.   

    主要是对Rectangle对象值的传递不是很明白哦,但是
    new 的时候直接初始化, Rectangle r=new Rectangle(10,10,50,50);试过了 还是0 0 0 0啊.
    为什么呢?还有 我关闭窗口时 不是hide了起来,而是直接把窗口关了啊!
    这又是怎么回事呢?
    我在eclipse3.5和EditPlus3.0里运行的都得了这样的结果
      

  5.   

    LZ你可以再细心的看下你的程序执行过程:
    main()中你先new了Hello了,于是调用你自己写的构造方法,构造方法中又new了一个Rectangle(不管你有没有设置这个Rectangel的参数),下面又调用了r=r.getBounds()于是将r定向为你所构造的Hello这个JFrame所获取的bound对象了,很明显你的Hello的Bound对象是0,0,0,0参数。然后你打印了。自此你的main方法中的第一条语句执行完了,然后继续执行下面的语句,下面的就不用我说了吧(你可以把main中的setBounds(20, 50, 100, 200);拿到你自己定义的构造方法的r=getBounds(r);前在看下)。hide是紧紧隐藏了你的Frame而并没有释放它所占用的系统资源。当你调用setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)方法时,程序退出,资源也被释放了。虽然两种在视觉上的效果是一样的,但是其内在的执行上是不一样的。