请解释为什么当我按下按钮2时没有任何反应,但是当我按下以下Java代码中的按钮1时,我得到了预期的结果

时间:2011-10-29 23:51:09

标签: java

我的代码只有按下“按钮1”才有效,但是当我按下“按钮2”时没有任何反应。 我知道我的paint()方法和if...else语句有问题,但不知道如何修复它。

谢谢

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

public class AnAppletWithButtons extends Applet implements ActionListener
{
    Button button1, button2;
    int r, g , b;
    Color color;
    boolean drawLine = false;
    boolean fillOval = false;

    public void init()
    {
        String parmStringRED =  getParameter("red");
        r = Integer.parseInt(parmStringRED);
        String parmStringGREEN =  getParameter("green");
        g = Integer.parseInt(parmStringGREEN);
        String parmStringBLUE =  getParameter("blue");
        b = Integer.parseInt(parmStringBLUE);
        color = new Color (r,g,b);
        button1 = new Button("Button 1");
        add(button1);
        button1.addActionListener(this);

        button2 = new Button("Button 2");
        add(button2);
        button2.addActionListener(this);
        button1.setForeground(color);
        button2.setForeground(color);

        button1.setBackground(Color.yellow);
        button2.setBackground(Color.yellow);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == button1) {
            System.out.println("Button 1 was pressed");
            drawLine = true;
        } else if (e.getSource() == button2) {
            System.out.println("Button 2 was pressed");
            fillOval = true;
        }
        repaint();
    }
    public void paint(Graphics g)
    {
        super.paint(g);   // for the background
        if(drawLine){
            System.out.println(drawLine);
            g.drawLine(0, 0, 400, 400);
        }
        else if(fillOval){
            System.out.println(fillOval);
            g.fillOval(10, 10, 390, 390);
        }

    }
}

3 个答案:

答案 0 :(得分:2)

您永远不会重置drawLinefillOval的值。只要您将drawLine设置为truepaint将始终绘制一条线,因为您首先检查该布尔值。

如果没有其他内容,您可以在false方法中将这两个变量重置为paint,但还有其他方法可以解决此问题。

答案 1 :(得分:0)

else if中的paint(Graphics g)分解为两个if s

答案 2 :(得分:0)

更改按钮点击事件处理程序,如下所示:

public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == button1) {
        System.out.println("Button 1 was pressed");
        drawLine = true;
        fillOval = false;
    } else if (e.getSource() == button2) {
        System.out.println("Button 2 was pressed");
        drawLine = false;
        fillOval = true;
    }
    repaint();
}

此致