jtan
jtan

Reputation: 129

How to get unique graphics context for embedded graphics components?

Consider the case where I have a JFrame and a JPanel object, with the JPanel object embedded inside the JFrame. My understanding was that each graphics component had its own graphics context. So my JFrame has its own graphics context and my JPanel has its own graphics context and these contexts are different. I put together a little test which seems to imply otherwise though:

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    frame.add(panel);

    Graphics frameContext = frame.getGraphics();
    Graphics panelContext = panel.getGraphics();

    if (frameContext == panelContext){
        System.out.println("The contexts are the same.");
    } else {
        System.out.println("The contexts are different.");
    }

The output is "The contexts are the same.". Why is this the case? Is it possible to have different graphics context for the JPanel and JFrame? I want to be able to draw to the JPanel graphics context, but not the JFrame context.

This question is related to Wrong JPanel displayed in CardLayout. Issues with getGraphics(). I believe the answer to this question might somehow solve the other.

Upvotes: 1

Views: 1079

Answers (1)

jtan
jtan

Reputation: 129

Wow. Dumb mistake on my part. The equality test was returning true because both were null.

The code should be changed to:

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    frame.add(panel);
    frame.setVisible(true);

    Graphics frameContext = frame.getGraphics();
    Graphics panelContext = panel.getGraphics();        

    if (frameContext.equals(panelContext)){
        System.out.println("The contexts are the same.");
    } else {
        System.out.println("The contexts are different.");
    }

After this modification, the output of the test is "The contexts are different." Therefore, this doesn't answer the question at Wrong JPanel displayed in CardLayout. Issues with getGraphics() .

Upvotes: 1

Related Questions