从组中选择一个JRadionButton并打印出一个int值

时间:2017-03-21 10:07:31

标签: java actionlistener radio-group

我有五个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

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

1 个答案:

答案 0 :(得分:0)

取决于你想要做的事情,但是使用你提供的代码片段,你可以通过提取两种方法来重构:

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());