0

我在顶部制作了borderX1-Y2的变量,但直到paint方法我才分配它们。我检查了方法中的值并且它们是正确的,但是当我在另一种方法中检查它们时它们是 0。我如何让它们保持它们的值?

public void paint(Graphics g)
{       
    borderX1 = 20;
    borderY1 = 20;
    borderX2 = getWidth();
    borderY2 = getHeight();

    g.setColor(Color.white);
    g.fillRect(0, 0, borderX2, borderY2);
    g.setColor(Color.blue);
    g.drawRect(borderX1, borderY1, borderX2 - 40, borderY2 - 40);
}

继承人的一切(我削减了不必要的位)

public class ShapePanel extends JPanel
{
private int borderX1;
private int borderY1;
private int borderX2;
private int borderY2;

public ShapePanel(){}

public void paint(Graphics g)
{
    borderX1 = 20;  
    borderY1 = 20;
    borderX2 = getWidth();
    borderY2 = getHeight();

    g.setColor(Color.white);
    g.fillRect(0, 0, borderX2, borderY2);
    g.setColor(Color.blue);
    g.drawRect(borderX1, borderY1, borderX2 - 40, borderY2 - 40);
}

public int getX1()
    {return borderX1;}

public int getY1()
    {return borderY1;}

public int getX2()
    {return borderX2;}

public int getY2()
    {return borderY2;}
}

我的错误出现在我的退货中,它们都返回 0 的值

我可以像这样初始化变量

private int borderX1 = 20;
private int borderY1 = 20;
private int borderX2 = 762;
private int borderY2 = 533;

但我希望 X2 和 Y2 的值根据窗口大小而改变

4

2 回答 2

0

Before call the value, you need to initialize value first. That you can do by call paint(Graphics g) first or globally initialize the value.

于 2013-09-28T15:15:21.597 回答
0

您正在使用不同的对象调用绘画和其他方法。请确保两者都是同一个对象。如果您调用paint 方法,然后调用具有相同对象的另一个方法,则值将被保留。

class Sample{
    int borderX1,borderY1,borderX2 ,borderY2 ;

    public void paint(Graphics g)
    {
       borderX1 = 20;
       borderY1 = 20;
       borderX2 = getWidth();
       borderY2 = getHeight();
     }
     public void fun1(Graphics g){

     }
 }

 Sample s1 = new Sample(); 
 s1.paint(Graphics)     borderX1 =20,borderY1=20,borderX2=some width ,borderY2 =some height
 Sample s2 = new Sample();
 s2.fun1();//borderX1=0,borderY1=0,borderX2=0 ,borderY2=0 these values should be 0 
于 2013-09-28T15:23:14.883 回答