我试图让我添加到JPanel的类,并在该类中运行一个函数。我创建了 MyButton
类的 JButton
,这个类我添加到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);
}
}
MyButton
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;
}
}
panel.getComponent(1).getText();
这将返回一个 Component
,它没有 getText()
方法。它需要投回一个 JButton
以便使用这种方法。
import java.awt.*;
import javax.swing.*;
public class ButtonText {
public static void main(String[] args) {
Runnable r = () -> {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2, 5));
for (int i = 0; i < 10; i++) {
panel.add(new JButton("Text " + (i+1)));
}
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Component[] components = panel.getComponents();
for (Component component : components) {
JButton b = (JButton) component;
System.out.println(b.getText());
}
};
EventQueue.invokeLater(r);
}
}
顺便说一下--要想得到元件,必须要在面板上翻来覆去地找,这似乎是一个糟糕的黑客。请看 XY问题是什么? 不管这里的实际目标是什么(&这个目标是什么?),在创建按钮时,将其存储在数组或列表结构中可能会更好。