1

I have 16 JLabel in a Map, and a JPanel. Now I want to check in that JPanel contains a JLabel or not among 16. I have tried this approach:

private int PanelContains(JPanel panel) {
    JLabel Value;
    for (Entry<Integer, JLabel> entry : Blackbox.entrySet()) {
        Value = entry.getValue();
        if (panel.getName() == Value.getParent().getName()) {
             return 1;
        }
    }
    return 0;
} 

I am comparing with their name. But I am getting "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" error on if (panel.getName() == Value.getParent().getName()) this line.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
prokawsar
  • 150
  • 1
  • 15
  • *"How to check a JPanel contains JLabel or not?"* Why? See [What is the XY problem?](http://meta.stackexchange.com/q/66377) – Andrew Thompson Apr 05 '16 at 23:09
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) 3) See [How do I compare strings in Java?](http://stackoverflow.com/q/513832/418556) .. – Andrew Thompson Apr 05 '16 at 23:09
  • .. 4) Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. – Andrew Thompson Apr 05 '16 at 23:12

2 Answers2

2

SwingUtilities contains a number of methods that could help you do this, but my guess is that getAncestorNamed might be the most useful:

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

A JLabel without a parent can cause this exception. Please try the code below.

private int panelContains(JPanel panel) {
    JLabel Value;
    for (Entry<Integer, JLabel> entry : Blackbox.entrySet()) {
        Value = entry.getValue();
        if (Value.getParent() == panel) {
             return 1;
        }
    }
    return 0;
} 
rdonuk
  • 3,921
  • 21
  • 39
  • Actually I meant a panel mean specific panel.All 16 Labels are situated in Panel also, Here I want to check for specific Panel. But in your code, it checks that, a JLabel situated on Panel or not, am I right ? But I don't want it. – prokawsar Apr 05 '16 at 18:08
  • It is checking if `Value` label is situated in the `panel` or not. – rdonuk Apr 05 '16 at 18:11
  • I think it will work as you want. Additionally, I realized that you are comparing strings with `==` which is wrong. Even if your way is correct you must compare strings with equals like that: `panel.getName().equals(Value.getParent().getName())`. – rdonuk Apr 05 '16 at 18:15