How to instantiate variable with name from a string? [duplicate]

三世轮回 提交于 2019-12-13 10:33:24

问题


Trying to get a better understanding of Swing and AWT with constructors, but now I have a question about constructors.

Based on whether or not the boolean maximize is true I want to set a new public boolean variable with the same value. Thing is I might need multiple JFrames but I can't have the same public variable name created if true. How do I instantiate a boolean with a name based off of a dynamic string

public void setJframe(JFrame name,  boolean maximize,) {

        if (maximize == true){
            name.setExtendedState(name.getExtendedState()|JFrame.MAXIMIZED_BOTH);
        }
        else {
            name.setLocationRelativeTo(null);
        }
}

Extra clarification

In the if part, it would be something like if it's remotely possible. The parenthesis are meant to indicate the whole variable name and inside a reflection mixed with a string

public boolean (getField(name) + "Max") = maximize;

I'm aware compilers do things a certain way just don't eat me alive if what I put here doesn't reflect that.


回答1:


Reflection views class & field definitions, and enables you to instantiate classes dynamically (by a variable name). It does not allow you to dynamically define fields or classes.

As Hovercraft says, you probably want a reference.

Using a variable enables you to reference the object you want, then set the existing 'property'/ or apply the behavior you want on that.

For example:

public void setupJFrame (JFrame frame, boolean maximize) {
    if (maximize) {
        frame.setExtendedState( frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
    } else {
        frame.setLocationRelativeTo(null);
    }
}

If you need to know on the 'JFrame' what state it is in, you could either subclass it to add a property storing that, or (perhaps better) just make a 'getter' or static 'getter' utility method to answer this using it's existing state.

public static boolean isFrameMaximized (JFrame frame) {
    if ((frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH)
        return true;
    return false;
}


来源:https://stackoverflow.com/questions/24005132/how-to-instantiate-variable-with-name-from-a-string

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