0

I am working on some code and was trying to add a border to a JPanel. I finally figured it out after someone told me, but I am not sure why my first line did not work. Can someone give me some insight? Here is the snip-it of code:

private Container currCntr;
currCntr = new JPanel();
currCntr.setBorder(new LineBorder(Color.BLACK));  //Doesn't work (cannot find symbol)
((JPanel)currCntr).setBorder(new LineBorder(Color.BLACK)); //Works
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28

3 Answers3

4

In the second line the JPanel is implicitly upcasted to a Container (an abstract super class of JPanel) which does not have a setBorder method.

The subsequent fix downcasts the container back to a JPanel which has and exposes the setBorder method as one of its public methods.

private Container currCntr = new JPanel(); //JPanel upcasted to type Container

//Container does not have a `setBorder` method
currCntr.setBorder(new LineBorder(Color.BLACK));

//Downcasted to JPanel which has the setBorder method
((JPanel)currCntr).setBorder(new LineBorder(Color.BLACK));
Community
  • 1
  • 1
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
-1

You need to cast to JPanel

((JPanel)currCntr).setBorder(new LineBorder(Color.BLACK));
1ac0
  • 2,875
  • 3
  • 33
  • 47
-1
Border border = BorderFactory.createLineBorder(Color.BLACK);
currCntr.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(10, 10, 10, 10)));

//you can try createLineBorder, shuld be the same syntax.

It because you did not set attributes for the line border. Please try set attributes. such as thickness.

1ac0
  • 2,875
  • 3
  • 33
  • 47