Java容器

时间:2014-02-13 11:48:05

标签: java swing jpanel

我正在处理一些代码,并试图为JPanel添加边框。有人告诉我后,我终于明白了,但我不确定为什么我的第一行不起作用。有人可以给我一些见解吗?这是代码片段:

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

3 个答案:

答案 0 :(得分:4)

在第二行中,JPanelimplicitly upcastedContainerJPanel的抽象超类),它没有setBorder方法。

后续修补程序将容器向下转发回JPanel,该setBorder具有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)); 方法作为其公共方法之一。

{{1}}

答案 1 :(得分:-1)

您需要转为JPanel

((JPanel)currCntr).setBorder(new LineBorder(Color.BLACK));

答案 2 :(得分:-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.

这是因为您没有为行边框设置属性。请尝试设置属性。如厚度。