Search code examples
javaswingjlabeljcomponent

How to determine if a component can be seen?


I have a panel, with a bunch of labels, in the middle of a frame. Some of the labels inside are not seen inside the panel cause of their location.

Here's a representation to see it better (the blue border is the panel; the green boxes inside it are the labels which are seen, while the red one's aren't)

enter image description here The labels are instantiated inside a for-loop like this...

for(int x = 0 ; x < 8 < x++){
  for(int y = 0; y < 11 < y++){
    Cell block = new Cell(); //Cell is a class that extends jlabel
    //code for setting block location here
    blockArray[x][y] = block;
    blockArray[x][y].setVisible(true);
    this.add(blockArray[x][y]);
  }
}

How can I determine if the labels (in my representation) are either green or red? Because my goal is to set the green ones to setVisible(true), while the red ones to setVisible(false).

I tried using isShowing and isDisplayable, but both returns false for all, by replacing the setVisible(boolean) line with something like this...

if(block[x][y].isShowing()) block[x][y].setVisible(true);
else{block[x][y].setVisible(false)}

The Cell objects has a setVisible(false) inside its constructor, pretty sure it doesn't effect my goal since I set them to true after instantiating them, but I might be wrong.


Solution

  • If they have a standard size you can calculate which labels are visible and which not (if your frame is resizeable you can always get its measures with JFrame.getSize(). If the labels vary in size for whatever reason, use JLabel.getSize() and JLabel.getLocation() to calculate if a label is displayed on the frame.