Call method in another class to set label text (don't use netbeans' default stuff)

独自空忆成欢 提交于 2019-12-24 08:22:00

问题


I'm using netbeans and want to edit the text in a label. I want to edit this label from another class in the main driver class. I have about 7 or 8 JDialog pages and let's say the label is on one of those pages.

When I try to call the method from one of those JDialogs so that I can edit it, it keeps asking for a java.awt.Frame. Where would I find that Frame name? Or, is there an easier way of editing labels from another class?

Netbeans makes labels private by default so I looked online and people have said making a setter method would be easiest.

QuickScreen is a .java file for instance...

public static void resetNumbers(){
    QuickScreen qs = new QuickScreen(some frame);
    qs.editLabel("Hello");
}

Please refer to my last comment on bmoran's solution.


回答1:


If you change the label you want to set to either default or protected level access, then you can set it from your dialog as long as both classes are in the same package (for default) or your dialog box extends the class that the label is in (protected).

    public class FrameClass extends JFrame {
        JLabel label1;// package access
        MyDialog dialog;

        //constructor *** Netbeans may have an init() method ***
        public FrameClass(){
        label1=new JLabel("Hello!");
        ...
        }

        ...
    }

public class MyDialog{
    public void changeLabel(){
        FrameClass.label1.setText("Good Bye!");
    }
}


来源:https://stackoverflow.com/questions/8928191/call-method-in-another-class-to-set-label-text-dont-use-netbeans-default-stuf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!