从 JPanel 获取 class

Get class from JPanel

我正在尝试获取我添加到 JPanel 的 class 和 运行 class.
中的一个函数 我创建了扩展 JButtonMyButton class,这个 class 我添加到 JPanel 但是在我添加这个 class 之后我想 运行 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;
}

}

panel.getComponent(1).getText();

这个returns一个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);
    }
}

顺便说一句 - 不得不通过面板拖回以获取组件似乎是一个糟糕的黑客攻击。请参阅 What is the XY problem? 无论这里的实际目标是什么(以及那个目标是什么?),在创建时将按钮存储在数组或列表结构中可能会更好。