0

I am developing a small screen capture application in java.i found a example to select rectangular area from here.(this is that question).i used another jframe and add a toggle button to call the Rectangular selection class.i create  a object of Rectangular selection class when the toggle button is selected . Now i have to questions,

  1. I used following code to create the selection class  object But if the selection  object  is exists it create a new object. How to stop this ?

     if (sn == null) {   
        if (btn_selection.isSelected()) {
            sn = new SnipIt();
        } else {
            sn.frame.dispose();
        }
    }
    

2.to close the selection  class it use this code line,

    SwingUtilities.getWindowAncestor(sl).dispose();

So i created a method  called closeSelection and insert above code line.but when i call this method returns a nullpointexception,

public void closeSelection() {
        SelectionPane sl=new SelectionPane();
        SwingUtilities.getWindowAncestor(sl).dispose();

    }

I know my code has many mistakes. So please show those and give me a solution.Highly appreciate your help  ☺

Community
  • 1
  • 1

1 Answers1

1
  1. For example by adding a simple condition if (sn == null) sn = new SnipIt();. null is the value when an object "does not exist".
  2. You have to use a reference to the actual sn Object from your first code snippet. Maybe store a reference to it in a field. Your attempt fails because:
    • it's an entirely different thing you try to get rid of (you make a new one just to dispose of it).
    • it's not attached to the actual view hierarchy so it doesn't have a window.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
zapl
  • 63,179
  • 10
  • 123
  • 154