java - 有没有办法在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");
解决方案
我不清楚您为什么要尝试以这种方式构建此接口,但这看起来像是一个多态性问题。
在您看来,duplicatePanel
是 a MyFirstPanel
,因为您在构造函数的第三行中以这种方式分配了它frame
。但是,当您声明它时,您仅将其声明为 a JPanel
,因此当您引用其中包含的按钮时,编译器不知道该按钮。解决您的问题的两个最快的方法是:
- 在开头声明
MyFirstPanel duplicatePanel
,而不是作为JPanel
.
或者
- 访问按钮时投射
duplicatePanel
为 aMyFirstPanel
(即((MyFirstPanel)duplicatePanel).button.setText("Button2");
)。
在更深的层次上,我觉得你在假设两个面板之间的关系并不存在(就复制而言——它们不是彼此的克隆或任何东西,它们只是都有按钮) ,但希望解决此问题将帮助您走向最终的学习目的地。
推荐阅读
- asp.net-core - Elastic Beanstalk appsettings.json 不工作
- python - 我有一个包含用户列表的 csv。我必须将这些用户与 AD 进行比较
- botframework - 如何避免从 Teams 桌面客户端启动固定应用程序时出现到达此应用程序错误的问题
- javascript - 在 ReactJS、React-Redux 中使用危险的 Set Inner html 和 MUI 富文本编辑器
- bash - 替换 csv bash 字符串中的元素
- cakephp - 我的 CakePHP 命令的解析器出现问题
- c# - Linq 查询显示比 SQL 替代方案更多的数据
- amazon-web-services - Step Functions - 等到 Glue Crawler 完成
- docker - 为什么我不能在带有 Docker 的远程服务器上使用 PhpStorm 和 Xdebug
- java - Springboot - MongoDb 查询耗时过长