简体   繁体   中英

How to Use Method from a Class that has been Passed in as a Variable

I have JLabels in multiple JFrames, and all of them serve the purpose of being a status indicator. In the class Controller , I have a method that changes the JLabel in the given JFrame. My question is that how do I reference the JFrame as a variable?

import javax.swing.*;

public class Controller {
    public static class Status {
        public static void vPrint(JFrame frame, String text) {
            JLabel label = frame.getConsoleLabel();
            label.setText(text)
        }
    }
}

So when I call it in the JFrame: Controller.Status.vPrint(this, "Set the JLabel Text.");

All of the JFrames have the method getConsoleLabel()

The problem is that when I call it, it says: cannot find symbol: method and I think the cause is that the variable frame isn't referenced.

Any solutions?

It seems like you are extending the JFrame to some Class but trying to invoke the getConsoleLabel() on the super class JFrame which doesn't have such method. So yes, you can't invoke getConsoleLabel on instance of JFrame no matter to which type the reference of this instance is referring to. Rather declare your own frame MyFrame extends JFrame which has implementation of getConsoleLabel() change the signature of vPrint with parameter type MyFrame and pass the required instance of type MyFrame to vPrint .

And DON'T USE MULTIPLE JFrame as Andrew has suggested. Follow the linked answer by him.

Well you specialized JFrames s have getConsoleLabel() method.

You have two solutions:

  1. Create an interface with getConsoleLabel() and make all of your JFrame s implement that interface. And change the signature of vPrint to accept an instance of your interface instead of JFrame .
  2. Create an class such as LabledFrame extends JFrame which has getConsoleLabel() and extend all of your JFrame s from that, and change the vPrint to accept an instance of LabledFrame instead of JFrame .

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