首页 > 解决方案 > 有没有办法在java中访问重复的JPanel的组件?

问题描述

例如:我想访问或更新复制的 JPanel 的按钮,例如

JPanel secondPanel = new JPanel();
secondPanel=(new MyFirstPanel());
//I tried to access the components using this code
duplicatedPanel.button.setText();

错误是它找不到符号 button1

//This is my full sample code
  class MyFirstPanel extends JPanel{
  JButton button=new JButton();
     public MyFirstPanel() {
     add(button);
     }
  }
//frame
class frame extends JFrame{
frame(){
    JPanel duplicatePanel=new JPanel();
    MyFirstPanel firstPanel=new MyFirstPanel();
    duplicatePanel=(new MyFirstPanel());
    firstPanel.button.setText("Button1");
    duplicatePanel.button.setText("Button2");
    add(firstPanel);
    add(duplicatePanel);
    setVisible(true);
    setLayout(new FlowLayout());
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String []args){
    new frame();
}

}

错误出现在duplicatePanel.button.setText("Button2");“找不到符号/变量按钮”中,有没有办法访问这个 duplicatedPanel 按钮?代码正在使用firstPanel.button.setText("Button1");

标签: java

解决方案


我不清楚您为什么要尝试以这种方式构建此接口,但这看起来像是一个多态性问题。

在您看来,duplicatePanel是 a MyFirstPanel,因为您在构造函数的第三行中以这种方式分配了它frame。但是,当您声明它时,您仅将其声明为 a JPanel,因此当您引用其中包含的按钮时,编译器不知道该按钮。解决您的问题的两个最快的方法是:

  1. 在开头声明MyFirstPanel duplicatePanel,而不是作为JPanel.

或者

  1. 访问按钮时投射duplicatePanel为 a MyFirstPanel(即((MyFirstPanel)duplicatePanel).button.setText("Button2");)。

在更深的层次上,我觉得你在假设两个面板之间的关系并不存在(就复制而言——它们不是彼此的克隆或任何东西,它们只是都有按钮) ,但希望解决此问题将帮助您走向最终的学习目的地。


推荐阅读