0

我可以从中获取面板名称ActionListener吗?

这是一些代码:

void models (int paneNum, int tabNum, String eQuery, String str, String title) throws SQLException {

    intoModels[paneNum] = new JPanel();
    intoModels[paneNum].setBackground(c);
    intoModels[paneNum].setLayout(new GridLayout(6, 2));

    ResultSet rs = DataBase.setConnection().executeQuery(eQuery);
    ButtonGroup modelRadioGroup = new ButtonGroup();

    while (rs.next()) {

        JRadioButton radio = new JRadioButton(rs.getString(str));
        radio.addActionListener(new radioButtonActionPerformed());
        modelRadioGroup.add(radio);
        intoModels[paneNum].add(radio);
    }

    intoModels[paneNum].setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
    panelsTab[tabNum].add(intoModels[paneNum]);
}

和一个监听器代码:

public class radioButtonActionPerformed implements ActionListener {
    public void actionPerformed(ActionEvent e){

        System.out.println("Selected radio: " + e.getActionCommand());
        selectedModel = e.getActionCommand();
    }
}

界面:在此处输入图像描述

我可以选择电台,但我无法从哪个面板注册。因此,我需要注册面板并将所选内容保存到第一个和第二个面板的索引 0 和 1 上的数组中。

4

1 回答 1

1

您是否尝试过component.getParent()获取父母的方法。

        public void actionPerformed(ActionEvent e) {
            Object src=e.getSource();
            if(src instanceof JRadioButton){
                Container parent=((JRadioButton)src).getParent();
                if(parent instanceof JPanel){
                    System.out.println(parent.getName());
                }
            }
        }
于 2014-03-23T11:40:36.647 回答