比如说,在JPanel上有一条(0,0,100,100)的线,如果我用鼠标拖动改变JPanel的大小(jpanel被加载在jframe中),希望该线的width和height能够与jpanel的width和height等比例变化。
小弟是gui的一个菜菜,希望各位大大能够不吝赐教,最好有个简单的演示代码,谢谢大家!

解决方案 »

  1.   

    getWidth(),getHeight()可以获得JPanel的宽和高度。
    及时改变画线参数就可以了。
      

  2.   

    我试过了,代码如下:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class drawline extends JPanel
    {
    private double x,y;
    private Rectangle p_rectangle = new Rectangle(200,200);
        private Rectangle n_rectangle = getBounds();
        public static JFrame frame = new JFrame("TreeDemo");;
        
    public void paint(Graphics g)
    {

    g.drawLine(0,0,(int)(x*100),(int)(y*100));
    }

    public drawline()
    {
    this.addHierarchyBoundsListener(new HierarchyBoundsListener(){
                public void ancestorResized(HierarchyEvent e)
                {
                 n_rectangle = getBounds();
                 x = n_rectangle.getBounds().width/p_rectangle.getBounds().width;
                 y = n_rectangle.getBounds().height/p_rectangle.getBounds().height;
                 p_rectangle = n_rectangle;
                 System.out.println("resize" + x);
                }
                
    public void ancestorMoved(HierarchyEvent e)
    {
       System.out.println("hello");
    }});
    }

    public static void main(String args[])
    {
    // JFrame frame;
        JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        //Create and set up the content pane.
            drawline dl = new drawline();
    dl.setOpaque(true); //content panes must be opaque  
    dl.addHierarchyBoundsListener(new HierarchyBoundsListener(){
    int i = 0;
                public void ancestorResized(HierarchyEvent e)
                {
                 System.out.println("resize" + x);
                }
                
    public void ancestorMoved(HierarchyEvent e)
    {
       System.out.println("hello");
    }});
        dl.setBounds(0,0,200,200);
        frame.setBounds(0,0,200,200);
            frame.setContentPane(dl);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    }
    }
      

  3.   

    但是当panel大小稍稍有一点变化时就会调用paint,这个时候原先的大小与变化的大小之间差别不大,所以相除以后还是1。
    mq612(五斗米)的思路是对的,可是在什么地方实施是一个关键。
    请各位帮帮忙看一下。
      

  4.   

    在那线的屁股下面加个JPanel,setLayout(new GridLayout(1,1)),或者用BorderLayout再把这个JPanel加原来JPanel下面
      

  5.   

    TO: diannaomingong(电脑民工)
    我还是不太明白,麻烦你能说再清楚些么?
    拜托了
      

  6.   

    定义一个容器。。
    con = getContentPane();
     然后直接布局为:con.setLayout(new FlowLayout(0));
     这样的话就是一个默认它就会随着你扩大而扩大