到目前为止,这是我完成的工作,我尝试添加ButtonGroup,但它一直向我显示错误T_T

public class tram extends JFrame implements ActionListener, KeyListener {

TextArea output = new TextArea(6, 30);
JButton cancel = new JButton("Cancel");
JButton exit = new JButton("Exit");

JRadioButton Single = new JRadioButton("Single");
JRadioButton Double = new JRadioButton("Double");
JRadioButton ZoneA = new JRadioButton("Zone A");
JRadioButton ZoneA_B = new JRadioButton("Zone A&B");


我在此处编写了Button.Group并更改了“ new JRadioButton();”。它没有用
我不确定是否应该使用if语句,因为找不到解决方法^。^“

public tram(){

    JLabel title = new JLabel("Please select the type of ticket you wish to purchase");


        setLayout(new BorderLayout());
        setSize(450, 300);
        setTitle("Redwich Tram");

        JFrame frm = new JFrame();

        JPanel top = new JPanel();
        top.setBackground(Color.white);
        top.add(title);
        title.setFont(new Font("Courier", Font.BOLD, 12));
        add("North", top);

        JPanel middle = new JPanel();
        middle.setBackground(Color.WHITE);
        top.add(new JLabel("Select an option by clicking one of the buttons"));
        add("Center", middle);
        middle.add(Single, BorderLayout.NORTH);
        Single.setBackground(Color.white);
        middle.add(Double, BorderLayout.CENTER);
        Double.setBackground(Color.white);
        middle.add(ZoneA, BorderLayout.SOUTH);
        ZoneA.setBackground(Color.white);
        middle.add(ZoneA_B, BorderLayout.SOUTH);
        ZoneA_B.setBackground(Color.white);


        middle.setBackground(Color.WHITE);
        middle.add(output);





        JPanel bottom = new JPanel();
        bottom.setBackground(Color.white);
        add("South", bottom);
        bottom.add(cancel,"South");
        cancel.setBackground(Color.white);
        bottom.add(exit,"South");
        exit.setBackground(Color.white);





        setResizable(false);
        setVisible(true);
    }

        public static void main(String[] args) {
        new tram();
    }

       public void onRadioButtonClicked(View view) {



       }




}

最佳答案

对于JRadioButton,您必须将它们添加到ButtonGroup并将按钮之一设置为选中状态。

Here is the Oracle tutorial

这是一个小例子:

JRadioButton b1 = new JRadioButton('option1);
b1.setSelected(true);

ButtonGroup g = new ButtonGroup();
g.add(b1);

09-28 12:30