为什么我的事件处理不起作用?

时间:2015-04-24 01:20:37

标签: java swing awt japplet

我是Stack Exchange和Java编程的新手。所以,我有这个程序使用JComponent来执行某些操作。

我有这个披萨绘制的图形,当我检查香肠复选框时,假设显示一堆棕色香肠。"

该程序编译正确,但它不会像检查盒子那样打印出香肠。任何帮助将非常感激。

以下是代码:

public class Baker2 extends JApplet implements ActionListener {

    Pizza myPizza;
    JCheckBox box1;
    Graphics g;

    public void paint(Graphics g) {
        super.paint(g);
        myPizza = new Pizza(300, 300);
        myPizza.drawPizza(g);
    }

    public void init() {
        setLayout(null);
        box1 = new JCheckBox("Sausage");
        box1.setBounds(500, 150, 100, 50);
        add(box1);
    }

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == box1) {
            Toppings t = new Sausage();
            t.drawToppings(g);
        }
    }
}

class Pizza extends JApplet {

    private static int height = 400;
    private static int width = 400;

    public Pizza(int width, int height) {
        //overloaded constructor
        this.width = width;
        this.height = height;
    }

    public void drawPizza(Graphics gr) {
        // draws basic pizza
        gr.setColor(Color.YELLOW);// dough
        gr.fillOval(100, 100, width, height);
        gr.setColor(Color.RED); //sauce
        gr.fillOval(125, 125, width - 50, height - 50);
    }
}

interface Toppings {

    public void drawToppings(Graphics gr);
}

class Sausage extends JApplet implements Toppings {

    private static int numberOf = 20;
    int[] x_coordinates;
    int[] y_coordinates;
    private Random r;
    Color BROWN = new Color(128, 128, 0);

    public void drawToppings(Graphics gr) {
        r = new Random();
        x_coordinates = new int[]{275, 210, 165, 150, 160, 167, 178, 189, 225, 280, 325,};
        y_coordinates = new int[]{195, 200, 250, 275, 189, 165, 181, 165, 260, 325, 350};
        for (int i = 0; i <= numberOf; i++) {
            gr.setColor(BROWN);
            gr.fillOval(x_coordinates[r.nextInt(x_coordinates.length)], y_coordinates[r.nextInt(y_coordinates.length)], 12, 12);
        }
        repaint();
    }
}

0 个答案:

没有答案