How can I change te background color of a Java applet?

Greetings,

So far, my code compiles, but it changes white to black and then don’t want to change. Supposely it should change from red->orange->green->pink->blue->black..

public void init() {
    c=new Color[] {Color.red, Color.orange, Color.green, 
                   Color.pink, Color.blue, Color.black };
    btnNext = new Button("Next Color");
    btnNext.addActionListener(this);
    setLayout(new BorderLayout());
    add(btnNext, BorderLayout.SOUTH);
}

public void paint(Graphics g) { }

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == btnNext) {
        for(int n=0;n<6;n++) {
            setBackground(c[n]);
        }
    repaint();
    }
}

Thank you for your help.

Answer

What you need to do is keep an int member variable of the current position in the array. Then increment that position every time you click the button.

// New int keeping track of background pos
private int arrPos;

public void init() {
    c=new Color[] {Color.red, Color.orange, Color.green, 
                   Color.pink, Color.blue, Color.black };
    // initialize the int
    arrPos = 0;
    btnNext = new Button("Next Color");
    btnNext.addActionListener(this);
    setLayout(new BorderLayout());
    add(btnNext, BorderLayout.SOUTH);
}

public void paint(Graphics g) { }

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == btnNext) {
        // increment the background
        arrPos++;
        if (arrPos >= c.length) arrPos = 0;
        setBackground(c[arrPos]);
        repaint();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *