简体   繁体   中英

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.

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();
    }
}

What's happening is that you're looping through all of the colors all at once, every time the btnNext action is triggered. It goes by so fast that you do not see the other colors.

What I would do is have a variable that keeps track of what position in the array you are in, and have that variable be incremented when the user hits next, and then change the background to that color. You have to get rid of the for loop inside your actionPerformed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM