简体   繁体   中英

java not able to call a second class

I'm trying to access a method from a class in java from my main class. The compiler seems to not understand what I am doing.

It shows the compiler error off: error cannot find symbol on the line mp = new getDataForDisplay(i);

What I am trying to do is access this method which assigns values to several global variables of that class to draw a rectangle.

This code is from my main class (simplified in certain areas)

main class
-some other classes here
-this is in my actionlistener...removed some irrelevant parts
  //show graph
            f1.add(new mainPanel(numProcc)); //shows data for graph
            f1.pack();
            processDetail.dispose();
            //call up process builder
            connect2c c = new connect2c (); // compile and run the C code

            int i = 0;
            String[] value = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
            mainPanel mp;
            while (i < numProcc)
            {
                c.returnData(value[i]);
                mp = new getDataForDisplay(i);
                //openFile f = new openFile (value[i]);
                i++;
            }

If you notice on the fifth line, I somehow manage to connect to the mainPanel class. I found this code online somewhere

This is the class I am trying to access, the method I am trying to access is getDataForDisplay()

class mainPanel extends JPanel
{
    int xCoor =0;
    int yCoor =0;
    int width =0;
    int height =0;
    public mainPanel(int x)
    {
       //constructor stuff here
    }

    public void getDataForDisplay (int a) 
    {
    //store in global variable

    //width = num of processes x 20
    //rect ->x,y,width,height
    //int a -> how many quantums, not using yet
    xCoor = 100;
    yCoor = 150;
    width = 50;
    height = 50;

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);   

    g.setColor(Color.RED);
    g.fillRect (xCoor, yCoor, width, height);

    }  
}

this line: mp = new getDataForDisplay(i); has plenty of syntactical errors: new someMethodCall(...) isn't allowed, getDataForDisplay(...) has returntype void, etc.. Correct would be

mp = new MainPanel();
mp.getDataForDisplay();

mp = new getDataForDisplay(i); makes no sense,

  • remove the new keyword if you want to call that method
  • mainPanel mp = new mainPanel(); if you want to create an object of type mainPanel
  • according to conventions, class names should start with uppercase, so mainPanel should be MainPanel

If you don't get the difference between class, object, methods, instantiation... well, I'd start from that before going any further

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM