0

I'm new to Programming and Java and building a small Application in JAVA with SQL and UI(Jframes)

In the log-in frame after the user enters his user name and password I do a SQL select query to search USER table for this user. If the query returns 1 single row, the login button event handler triggers and the object of the next frame is created.

few frames later I have an SQL insert activity where I also have to insert the USER_ID of the person initiating the insert(the current logged in user).

What is the best practice to pass this information across a series of frame classes?

My initial idea is to pass the user_id as a parameter in the object so it gets set in the constructor of each frame class. but the problem is not all my frames really need this data. Only the final frame involved with the insertion needs the user ID. but in-order to get to that frame I have to pass through all other frames. This doesn't seem like a good practice.

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • Take a look at [The Use of Multiple JFrames: Good or Bad Practice?](https://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-or-bad-practice) . – George Z. Jul 06 '19 at 08:59

1 Answers1

1

First Approach

The first possibility I thought of was to use java.util.Properties to store the application state inside of a properties file. The approach would be to use a singleton wrapper, let's say ApplicationState for reading/writing to properties file. This singleton class would be reachable from all frames, alternatively an instance of this class could be passed inside of constructor.

public class ApplicationState {

    private static ApplicationState instance = new ApplicationState();

    private ApplicationState() { }
    public static ApplicationState getInstance( ) { return instance; }

    public String read(String key) throws IOException {

        try (InputStream input = new FileInputStream("path/to/config.properties")) {

            Properties prop = new Properties();
            prop.load(input);
            return prop.getProperty(key);
        }
    }

    ...
}

Second Approach

Then I realized that a much cleaner solution would be to use the java.util.prefs.Preferences API. See Preferences API for details.

class A {

    public void login() {

        Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

        prefs.putInt("userId", 11);
        ...
    }
}

class B {

    public void insert() {

        Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

        int userId = prefs.getInt("userId", 0); // 0 is default identifier
        ...
    }
}

In addition because you want to store sensitive information, encrypted storage would be useful. For using encrypted preferences see this article.

0x1C1B
  • 1,204
  • 11
  • 40