首页 > 解决方案 > 为什么程序在我的 showPanel 方法中的 setVisible 处抛出错误“找不到符号”?

问题描述

为什么该setVisible方法会抛出错误,说我的方法中找不到符号showPanel?这没有意义,因为我引用的是JPanel存储在 an 中的,ArrayList所以它应该能够使用setVisible.

public class mainFrame extends javax.swing.JFrame {

/**
 * Creates new form mainFrame
 */
private ArrayList list;
public mainFrame() {
    initComponents();
this.setSize(500,500);
    int h=this.getHeight();
    int w=this.getWidth();

    homePanel homePnl = new homePanel();
    this.add(homePnl);
    homePnl.setLocation(0,0);
    homePnl.setSize(w,h);
    homePnl.setVisible(true);

    DeploymentInfoPanel infoPanel = new DeploymentInfoPanel();
    this.add(infoPanel);
    infoPanel.setLocation(0,0);
    infoPanel.setSize(w,h);

    atomServerPanel atomPnl = new atomServerPanel();
    this.add(atomPnl);
    atomPnl.setLocation(0,0);
    atomPnl.setSize(w,h);

    autoDeploymentPanel autoPnl = new autoDeploymentPanel();
    this.add(autoPnl);
    autoPnl.setLocation(0,0);
    autoPnl.setSize(w,h);

    list = new ArrayList<>();
    list.add(homePnl);
    list.add(infoPanel);
    list.add(atomPnl);
    list.add(autoPnl);


    this.pack();
}

public void showPanel(int panelNum){
    list.get(1).setVisible(true);
}

标签: javaswingjpanel

解决方案


private ArrayList list;

您没有指定将添加到 ArrayList 的对象类型。所以默认情况下 get() 方法会返回一个 Object 的实例。没有 setVisible(...) 方法Object

当您定义 ArrayList 时,您应该使用:

private ArrayList<Component> list;

现在编译器知道您正在向ComponentArrayList 添加实例。

事实上,编译器会检查以确保您只添加Component.

它还会在您编译时消除警告消息。

类名也应以大写字符开头。有时你会,有时你不会:

DeploymentInfoPanel infoPanel = new DeploymentInfoPanel();
...
atomServerPanel atomPnl = new atomServerPanel();
...
autoDeploymentPanel autoPnl = new autoDeploymentPanel();

请注意论坛如何突出显示正确命名的类以使代码更易于阅读?

遵循 Java 约定并保持一致。

最后,要在框架的同一区域显示多个面板,您应该使用Card Layout


推荐阅读