簡體   English   中英

Java對象值不一致

[英]Java Object values not consistent

我找不到其他解決方案,因為我不確定如何用足夠多的詞來描述它。

當我分配activeList ,這是一個字段currentActiveList在隨機生成的矩形ActiveList其接收的值就好類。

public class ActiveList {
    Rectangle[] activeList = new Rectangle[10];

    public ActiveList() {
        for(int i = 0; i < activeList.length; i++)
            activeList[i] = null;
    }

    public void addToList(Rectangle x) {
        for(int i = 0; i < this.activeList.length; i++) {
            if(this.activeList[i] == null) {
                this.activeList[i] = x;
                i = this.activeList.length+1;
            }

            else
                this.activeList[activeList.length-1] = x;
        }
    }

    public Rectangle[] getActiveList() {
        return this.activeList;
    }

    public int getLength() {
        //System.out.print(this.activeList.length);
        return this.activeList.length;
    }

    public void deleteFromList(int x) {
        this.activeList[x] = null;
    }

    public Rectangle getFromList(int x) {
        Rectangle retVal = this.activeList[x];
        //System.out.println("Returning getFromList(int x): " +retVal);
        return retVal;
    }

    public void genRandomRectangle() {
        Random randomNumberGenerator = new Random();
        double[] pointVal = new double[4];
        double randomInt = randomNumberGenerator.nextInt(400-10);
        pointVal[0] = randomInt;
        randomInt = randomNumberGenerator.nextInt(400-10);
        pointVal[1] = randomInt;
        randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[0]));
        if(randomInt < 5) {
            randomInt = randomInt+pointVal[0]+5;
        }

        else
            pointVal[2] = randomInt+pointVal[0];

        randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[1]));
        if(randomInt < 5) {
            randomInt = randomInt+pointVal[1]+5;
        }

        else
            pointVal[3] = randomInt+pointVal[1];

        Rectangle newRandom = new Rectangle(pointVal[0], pointVal[1], pointVal[2], pointVal[3]);
        //System.out.println(pointVal[0]);
        //System.out.println(pointVal[1]);
        //System.out.println(pointVal[2]);
        //System.out.println(pointVal[3]);
        System.out.println("New Random: " +newRandom);

        addToList(newRandom);
    }
}

然而,當我嘗試在我的主類中使用這些值GraphicGen ,該currentActiveList對所有的索引返回空值。

public class GraphicGen extends JPanel {
    ActiveList currentActiveList = new ActiveList();
    public static int gridSpaceX = 400;
    public static int gridSpaceY = 400;
    static JFrame mainFrame = new JFrame();

    protected void paintComponent(Graphics g) {
        //super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //int w = getWidth();
        //int h = getHeight();
        // Draw ordinate.
        //g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
        // Draw abcissa.
        //g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
        //double xInc = (double)(w - 2*PAD)/(data.length-1);
        //double scale = (double)(h - 2*PAD)/maxValue();
        // Mark data points.
        //g2.setPaint(Color.red);

        double[] coords = new double[4];
        //g2.fill(new Ellipse2D.Double(coords[0], coords[1], 4, 4));
        //g2.fill(new Ellipse2D.Double(coords[2], coords[3], 4, 4));
        //g2.fill(new Ellipse2D.Double(100, 100, 4, 4));
        System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
        System.out.println("Ya drew a new Main GUI!");
        System.out.println("currentActiveList.getActiveList(): " +currentActiveList.getActiveList());
        for(int i = 0; i < currentActiveList.getLength(); i++) {
            //System.out.println("currentActiveList.getFromList(i): "+currentActiveList.getFromList(i));
            //System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
            //System.out.println(activeList.getFromList(i).getTopLeftX());
            if(currentActiveList.getFromList(i) != null) {
                coords[0] = currentActiveList.getFromList(i).getTopLeftX();
                System.out.println(coords[0]);
                coords[1] = currentActiveList.getFromList(i).getTopLeftY();
                System.out.println(coords[1]);
                coords[2] = currentActiveList.getFromList(i).getBottomRightX();
                System.out.println(coords[2]);
                coords[3] = currentActiveList.getFromList(i).getBottomRightY();
                System.out.println(coords[3]);
                g2.draw(new Line2D.Double(coords[0], coords[1], coords[2], coords[1]));
                g2.draw(new Line2D.Double(coords[0], coords[1], coords[0], coords[3]));
                g2.draw(new Line2D.Double(coords[2], coords[1], coords[2], coords[3]));
                g2.draw(new Line2D.Double(coords[0], coords[3], coords[2], coords[3]));
            }
        }

        /*double x = 50;
        double y = 50;
        g2.fill(new Ellipse2D.Double(x, y, 4, 4));*/
        /*for(int i = 0; i < data.length; i++) {
            double x = PAD + i*xInc;
            double y = h - PAD - scale*data[i];
            g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
        }*/
    }

    /*private int maxValue() {
        int max = data[0];
        for(int i = 0; i < data.length; i++) {
            if(data[i] > max)
                max = data[i];
        }
        return max;
    }*/

    public void callRepaintOnMain() {
        mainFrame.repaint();
    }

    public void callGenRandom() {
        currentActiveList.genRandomRectangle();
    }

    public static void main(String[] args) {
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.add(new GraphicGen());
        mainFrame.setSize(gridSpaceX, gridSpaceY);
        ButtonPrompt buttonPrompter = new ButtonPrompt();
        mainFrame.setLocation(200,200);
        mainFrame.setVisible(true);
    }
}

動作生成器將調用隨機生成器方法。

public class ButtonPrompt extends GraphicGen {

    ActionListener actionListenerRandom = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
          //currentActiveList.genRandomRectangle();
            callGenRandom();
            callRepaintOnMain();
        }
    };

    JButton randomBtn = new JButton("Add Random Rectangle");        
    JButton inputCoordinates = new JButton("Input Rectangle Coordinates");

    public ButtonPrompt() {
        JFrame f = new JFrame("Add Rectangles");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BoxLayout boxLayout = new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS);
        f.setLayout(boxLayout);

        randomBtn.addActionListener(actionListenerRandom);

        f.setSize(200, 200);
        f.setLocation(600, 200);
        f.setVisible(true);
        f.add(randomBtn);
        f.add(inputCoordinates);
        f.pack();
    }
}

這是范圍界定或引用問題嗎? 我真的很茫然。

您的實際問題還不清楚,但是僅閱讀前兩種方法就足以發現我認為是一個錯誤:

public ActiveList() {
    for(int i = 0; i < activeList.length; i++)
        activeList[i] = null;
}

上面的代碼完全沒用。 對象數組的元素的默認值為null。 因此,循環將null分配給已經為null的變量。

public void addToList(Rectangle x) {
    for(int i = 0; i < this.activeList.length; i++) {
        if(this.activeList[i] == null) {
            this.activeList[i] = x;
            i = this.activeList.length+1;
        }

        else
            this.activeList[activeList.length-1] = x;
    }
}

如果列表僅包含null,則矩形將存儲在索引0處,並且循環將停止。 對於此方法的所有后續調用,循環將發現索引0處的元素不為null,因此將x存儲在數組的最后一個索引處,然后存儲在第一個非null索引處。

我不確切地知道您要實現的目標以及實際的問題是什么,但是您可能應該忘記基於數組來實現自己的列表,而應該使用ArrayList。

這里:

public static void main(String[] args) {
    ...
    mainFrame.add(new GraphicGen());
    ...
    ButtonPrompt buttonPrompter = new ButtonPrompt();
}

ButtonPrompt 擴展了 GraphicGen ,它是一個JPanel ButtonPrompt的構造函數中,您創建了一個JFrame並向其中添加了兩個JButton

因此,當您的應用程序啟動時,屏幕上將有兩個JFrame,一個是mainFrame ,其中包含一個GraphicGen ,另一個是buttonPrompter ,其中包含兩個按鈕。

當您單擊按鈕時,會調用actionPerformed() ,並且實際上是在調用buttonPromptercallGenRandom()如果隨機生成邏輯正確,則將生成的矩形添加到buttonPrompter 但是您沒有將此buttonPrompter添加到任何一個JFrame ,您將看不到它。


您可能想要什么:

ButtonPrompt不延長GraphicGen ,而是給ButtonPrompt的的參考GraphicGen您添加到mainFrame

public class ButtonPrompt extends GraphicGen {
    JButton randomBtn = new JButton("Add Random Rectangle");        
    JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
    final GraphicGen gg;

    public ButtonPrompt(GraphicGen gg) {
        this.gg = gg;
        ......

        ActionListener actionListenerRandom = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                gg.callGenRandom();
                gg.callRepaintOnMain();
            }
        };

        randomBtn.addActionListener(actionListenerRandom);

        ......
    }
}

並在您的main()

public static void main(String[] args) {
    ...
    GraphicGen gg = new GraphicGen();
    mainFrame.add(gg);
    ...
    ButtonPrompt buttonPrompter = new ButtonPrompt(gg);
}

而且,代碼還有其他問題。

例如, GraphicGenJPanel主類,它具有JFrame的字段,該字段實際上在應用程序運行時包含GraphicGen實例-這看起來很糟。 我對Swing不太了解...是否必須調用包含JFramerepaint()而不是僅調用JPanelrepaint() (如果有)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM