简体   繁体   中英

How do I change the color of my Java button?

So I am trying to learn swing and having some trouble trying to change he color of my button. What I want to do is to create a custom button that have three different states, UP, DOWN, and MISSING. UP should show a Icon, down should be blue and MISSING should be white.

The problem is that it seems like I can not change the color "inside" the class using the enum's but instead have to create a new class or change the background color outside of the class, witch would make the enums pointless. Where am I messing up?

import java.awt.*;
import javax.swing.*;
import static javax.swing.JOptionPane.*;

public class Card extends JButton {

    Icon icon;
    Status status;

    public enum Status {
    MISSING, DOWN, UP
    }

    public Card(Icon icon) {
    this.icon = icon;
    setStatus(Card.Status.MISSING);
    }

    public Card(Icon icon, Status status){
    this.icon = icon;
    setStatus(status);  
    }

    public Card(Status status) {
    setStatus(status);
    }

    public void setStatus(Status newStatus) {
    this.status = newStatus;
    switch(status){
    case MISSING:
        this.setBackground(Color.white);
    case DOWN:
        this.setBackground(Color.blue);
    case UP:
        this.setIcon(icon);
    }
    }

    public Status getStatus() {
    return this.status;
    }  
}
case MISSING:
        this.setBackground(Color.white);
    case DOWN:
        this.setBackground(Color.blue);
    case UP:
        this.setIcon(icon);

This will end up in waterfall. Change your code to this:

case MISSING:
        this.setBackground(Color.white);
        break; // ends the switch block in case of missing
    case DOWN:
        this.setBackground(Color.blue);
        break; // ends the switch block in case of down
    case UP:
        this.setIcon(icon);

If you don't do this, the waterfall principle will execute all following case blocks, leading each and every option to execute this.setIcon(icon); as final statement for each case, and this.setBackground(Color.blue); as color for both missing and down.

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