有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java向JPanel添加标签并添加Eclipse中不建议的方法

这似乎是一个非常新的问题,但我似乎找不到这种情况的答案。 How to Use Panels教程说JPanel中有一个add()方法,但我无法在代码中实现它

public class JPanelTest extends AbstractView {
   private final JPanel panel;

 public JPanelTest () {
   this.panel = new JPanel(new BorderLayout());
 }

 private void initComponents() {
   JLabel label = new JLabel("label testing ");
   this.panel.add(label);
 }
}

AbstractView是一个抽象类,它扩展了JPanel并实现了ViewSupportPropertyChangeListener

在代码的最后一行this.panel.add(label);给出了一个编译错误。 我没有看到Eclipse中建议的Panel.add()。 建议的添加相关方法有addAncestorListeneraddNotifyaddVetoableChangeListener

我怎么能在建议框中看不到简单的add方法? 我正在使用Eclipse的1.6编译级别。那会有区别吗

提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    您创建了JPanel面板,但没有添加任何内容。是的,它正在接收JLabel,但是因为JLabel和panel JPanel都没有添加到主GUI窗口(JFrame?)显示的任何内容中没有显示

    解决方案:将panel JPanel或JLabel本身添加到this对象(有望添加到顶层窗口/JFrame)

    因此,要么:

    private void initComponents() {
       JLabel label = new JLabel("label testing ");
       this.panel.add(label);
       this.add(panel);
    }
    

    private void initComponents() {
       JLabel label = new JLabel("label testing ");
       // this.panel.add(label);
       this.add(label);
    }
    
  2. # 2 楼答案

    你从哪里得到AbstractView的?它不是Swing hierachy的内置程序

    基于您的类名,您可能希望扩展JPanel而不是AbstractView

    public class JPanelTest extends JPanel {