2

该程序有 2 个单选按钮。1:用于圆形,2:用于输出正方形。

该程序基本上设计为基于单选按钮组输出圆形或方形。

我的问题是我不知道如何在按钮上实现动作侦听器以输出形状。当我调用方法 fm 时,初始化单选按钮时出现错误。显然我认为我需要一个主要的方法。

请记住,这是 java AWT。

如果您希望我添加更多详细信息或澄清,请发表评论。

    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.applet.Applet;

    public class RadioButton extends Applet
implements ActionListener
    {
        int choice;

        Frame fm = new Frame ("RadioButton Group");
        Label la = new Label ("What shape do you want to draw?:");
        fm.setLayout (new GridLayout (0, 1));
        CheckboxGroup cg1 = new CheckboxGroup ();
        fm.add (la);

        fm.add (new Checkbox ("CIRCLE", cg1, true));
        fm.add (new Checkbox ("SQUARE", cg1, true));

        fm.setSize (250, 200);
        fm.setVisible (true);
        fm.addWindowListener (new WindowAdapter ()


        {

            public void paint (Graphics g)  // How can you 'update the drawing' or repaint it?
            {
                switch (choice) // Maybe for colors if all else fails you can add a switch 'within' a switch. Inefficient-yes but helps.
                {
                    case 1:
                        if (choice == 1)
                            g.fillOval (30, 40, 20, 20);

                    case 2:
                        if (choice == 2)
                            g.fillRect (20, 40, 20, 20);
                        break;
                }
            }
            public void actionPerformed (ActionEvent evt)
            {
                if (evt.getSource () == "CIRCLE")
                    choice = 1;
                else
                    choice = 2;
            }
            public void windowClosing (WindowEvent we)
            {
                System.exit (0);
            }
        }


        );
    }
    }
4

1 回答 1

2

您可以使用项目侦听器。这是一个完整的工作示例:

import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;


import javax.swing.JFrame;


public class Project1 extends JFrame implements ItemListener {

    CheckboxGroup cg1 = new CheckboxGroup ();       //create group
    Checkbox c1 = new Checkbox("Circle",cg1,true);  //circle button
    Checkbox c2 = new Checkbox("Square",cg1,true);  //square button

    public Project1() {
        setLayout(new FlowLayout());        

        //add listeners
        c1.addItemListener(this);
        c2.addItemListener(this);

        //add to frame
        add(c1);
        add(c2);

        //set visible
        this.setVisible(true);
    }


    @Override
    public void itemStateChanged(ItemEvent e) 
    {
        //c1 = circle
        //c2 = square
        if(e.getSource() == c1)
            System.out.println("Circle");
        else
            System.out.println("Square");

    }

    public static void main(String[] args) {
        Project1 p = new Project1();
    }
}

将其保存为完整的 .java 并运行它。应该给你一个体面的例子来说明如何完成你所寻找的。

于 2013-03-06T16:09:10.630 回答