Select 来自组的一个 JRadionButton 并打印出一个 int 值

Select a JRadionButton from group and print out an int value

我有五个 RadionButtons,值从 1 到 5。根据我的选择,我想打印出值。

    JRadioButton rOneStar = new JRadioButton();
    rOneStar.setActionCommand(Integer.toString(1));
    JRadioButton rTwoStars = new JRadioButton();
    rTwoStars.setActionCommand(Integer.toString(2));
    JRadioButton rThreeStar s= new JRadioButton();
    rThreeStars.setActionCommand(Integer.toString(3));
    JRadioButton rFourStars = new JRadioButton();
    rFourStars.setActionCommand(Integer.toString(4));
    JRadioButton rFiveStars = new JRadioButton();
    rFiveStars.setActionCommand(Integer.toString(5));


    // group stars
    ButtonGroup starGroup = new ButtonGroup();
    starGroup.add(rOneStar);
    starGroup.add(rTwoStars);
    starGroup.add(rThreeStars);
    starGroup.add(rFourStars);
    starGroup.add(rFiveStars);

现在我有多个打印出值的 ActionListener。但在我看来,代码太多了。

        rOneStar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                e.getActionCommand();
                 System.out.println(starGroup.getSelection().getActionCommand());
            }
        });
        rTwoStars.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                e.getActionCommand();
                 System.out.println(starGroup.getSelection().getActionCommand());
            }
        });
        ... and so on

任何人都可以给我一个提示,告诉我如何缩短我的代码吗?

取决于您想进一步做什么,但是使用您提供的代码片段,您可以通过提取两种方法来重构一下:

private JRadioButton createJRadioButton(int x){
    final JRadioButton rXStar = new JRadioButton();
    rXStar.setActionCommand(Integer.toString(x));
    return rXStar;
}

private ActionListener createActionListener(){
 return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                e.getActionCommand();
                 System.out.println(starGroup.getSelection().getActionCommand());
            }
        };
}

这将减少您的代码并使它更好一些,如下所示:

JRadioButton rOneStar = createJRadioButton(1);
JRadioButton rTwoStars = createJRadioButton(2);
JRadioButton rThreeStar = createJRadioButton(3);
JRadioButton rFourStars = createJRadioButton(4);
JRadioButton rFiveStars = createJRadioButton(5);

// group stars
ButtonGroup starGroup = new ButtonGroup();
starGroup.add(rOneStar);
starGroup.add(rTwoStars);
starGroup.add(rThreeStars);
starGroup.add(rFourStars);
starGroup.add(rFiveStars);

rOneStar.addActionListener(createActionListener());
rTwoStars.addActionListener(createActionListener()); 
rThreeStars.addActionListener(createActionListener());
rFourStars.addActionListener(createActionListener());
rFiveStars.addActionListener(createActionListener());