我有一堆动态添加的面板,其中包含单选按钮和一个带有多个标签的面板绑定到单选按钮。假设我有一个按钮应该检索带有标签的容器绑定到选定的单选按钮,或者让我们说另一个词 - 数据绑定到选定的单选按钮。但是如何获得这个容器呢?
这是我尝试执行此操作的代码(实际上,这是一个显示 UI(视图)端正在发生的事情的存根):
public class Test extends JFrame {
public static ButtonGroup radioButtons = new ButtonGroup();
public Test() {
super("Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(200, 300);
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.add(new PanelWithRadioButton("text1", "text2"));
panel.revalidate();
}
});
panel.add(addButton);
JButton infoButton = new JButton("Info");
infoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(Enumeration<AbstractButton> myRadioButtons = radioButtons.getElements();
myRadioButtons.hasMoreElements();) {
JRadioButton btn = (JRadioButton) myRadioButtons.nextElement();
if(btn.isSelected()) {
PanelWithTwoLabels panelWithLabels = (PanelWithTwoLabels) btn.getComponent(1); //Trying to get Component bind to selected JRadioButton
JOptionPane.showMessageDialog(null, "Text1: " + panelWithLabels.getLabel1Text() + ", Text2: " + panelWithLabels.getLabel2Text());
}
}
}
});
panel.add(infoButton);
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
//JRadioButton + Panel with two text fields
private class PanelWithRadioButton extends JPanel {
private JRadioButton rButton;
private PanelWithTwoLabels panelWithTwoLabels;
public PanelWithRadioButton(String text1, String text2) {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
panelWithTwoLabels = new PanelWithTwoLabels(text1, text2);
rButton = new JRadioButton();
rButton.add(panelWithTwoLabels); //Bind Component to JRadioButton
radioButtons.add(rButton);
add(rButton);
add(panelWithTwoLabels);
}
}
private class PanelWithTwoLabels extends JPanel {
private JLabel label1;
private JLabel label2;
public PanelWithTwoLabels(String text1, String text2) {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
label1 = new JLabel(text1);
label2 = new JLabel(text2);
add(label1);
add(label2);
}
private String getLabel1Text() {
return label1.getText();
}
private String getLabel2Text() {
return label2.getText();
}
}
}