如何动态添加 JPanel 并使其可点击?

How to add JPanel Dynamically and making it clickable?

我正在尝试创建一个基本的 gui 程序,旨在:

  1. 动态插入可滚动的 JPanel(将创建的 JPanel 的数量基于我的列表的大小)。
  2. 点击时从 JPanel 获取信息。

到目前为止,这是我所做的:

...

public class BeesFrame extends javax.swing.JFrame {
    List<String> bees = new ArrayList<>(Arrays.asList("Bee 1", "Bee 2", "Bee 3",
                                                    "Bee 4", "Bee 5", "Bee 6",
                                                    "Bee 7", "Bee 8", "Bee 9",
                                                    "Bee 10", "Bee 11", "Bee 12",
                                                    "Bee 13"));
    GridBagLayout layout = new GridBagLayout();

    JScrollPane scrollpane;
    JPanel beesPanel;
    JPanel beesCell;
    JLabel label;

    public BeesFrame() {
        initComponents();
        label = new JLabel();
        for(int i = 0; i < bees.size(); i++){
            beesCell = new JPanel();
            beesCell.setName(bees.get(i));
            beesCell.setPreferredSize(new Dimension(100, 100));
            beesCell.setMinimumSize(new Dimension(100, 100));
            beesCell.setBackground(Color.yellow);

            label.setHorizontalTextPosition(SwingConstants.CENTER);
            label.setText(beesCell.getName());

            beesCell.add(label);
            beesCell.validate();
            beesCell.repaint();
            System.out.println(bees.get(i));
        }

        beesMainPanel.setLayout(new GridLayout((bees.size()/4)+1, 4, 1, 1));
        beesMainPanel.add(beesCell);
        beesCell.setVisible(true);
        beesCell.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e){
                JPanel panel = (JPanel) getComponentAt(e.getPoint());
                panel.setName(label.getText());
                outPut(panel);
            }
        });

        beesCell.validate();
        beesCell.repaint();

    }

    void outPut(JPanel panel){
        System.out.println("Panel...."+panel.getName());
    }

... // some other code generated by Netbeans


}

但不是正确显示。只有我列表中的最后一个被插入,如果我点击它,它说 javax.swing.JRootPane 不能转换为 javax.swing.JPanel。这是发生的错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JRootPane cannot be cast to javax.swing.JPanel
    at catchingbees.frame.BeesFrame.mousePressed(BeesFrame.java:79)
    at java.awt.Component.processMouseEvent(Component.java:6530)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    ...

这是我输出的屏幕截图:

但这就是我打算做的:

非常感谢任何帮助。

将 MouseListener 添加到每个面板,然后您只需使用 MouseEvent 的 getSource() 方法来访问被单击的面板。

MouseListener ml = new MouseAdapter()
{
    @Override
    public void mousePressed(MouseEvent e)
    {
        JPanel panel = (JPanel)e.getSource();

        // do your processing on the panel
    }
}

然后在创建面板的循环中,您只需执行以下操作:

panel.addMouseListener( ml );