【发布时间】:2020-05-22 16:47:37
【问题描述】:
我正在尝试获取我添加到 JPanel 的类并在该类中运行一个函数。
我创建了扩展JButton 的MyButton 类,这个类我添加到了JPanel,但是在我添加了这个类之后,我想在这个对象上运行getText()。
我试过了,但它无法识别该功能:
panel.getComponent(1).getText();
主要
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2, 5));
for (int i = 0; i < 10; i++) {
panel.add(new MyButton());
}
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
我的按钮
public class MyButton extends JButton {
private String text;
public MyButton()
{
this.text="Hello";
setText("test");
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
【问题讨论】:
-
这能回答你的问题吗? Java get JPanel Components
-
(1-) 您在上一个问题中被要求提供minimal reproducible example。你一发帖,你就得到了答案。你的“MRE”在哪里。每个问题都应该有一个“MRE”。我们不知道您的代码的上下文,我们不知道您实际调用
panel.getComponent(1).getText();的原因或位置。一个问题应该用“MRE”完成,这样我们才能理解上下文。另外,为什么要创建自定义类。 JButton 已经有一个setText(…)方法。不要重新发明轮子。 -
看起来您在调用自定义方法之前还没有进行转换。 String text = ((MyButton) panel.getComponent(1)).getText();
-
MyButton extends JButton我还没有看到扩展按钮的充分理由。你的是什么?同意@camickr re MRE。在我的编辑器中编译代码之前,我不会认真考虑大多数问题。 -
@AndrewThompson,很惊讶您为 OP 编写了 MRE。 OP 不仅没有听取在每个问题上发布 MRE 的建议,而且在创建 GridLayout 时仍然使用行/列参数,OP 完全忽略了您在上一个问题中提供的答案。