user3773246
user3773246

Reputation:

How to repaint in Java

I'm taking a course in GUI programing. I'm having a hard time understanding how to use the repaint my Box class to a different color. Here is my GUI class:

public class Box extends JPanel {

    private Color color;
    private int boxNumber;


    public Box(Color color, int boxNumber){
        this.boxNumber = boxNumber;
        this.color = color;
    }

    public void changeColor(){
        setBackgroundColor(Color.WHITE);
        repaint();
    }

    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        setBackground(color);
    }
}

Here is where I add it to Frame:

public class MainHeader {

    Box box[];
    public MainHeader(){

    }

    private void setBox(){

        box = new Box[4];
        Color color[] = {Color.RED, Color.YELLOW, Color.BLUE, Color.ORANGE};

        for(int i = 0; i < color.length; i ++){
            box[i] = new Box(color[i],i);
        }
    }

    private void gui(){
        JFrame f = new JFrame();
        f.setLayout(new GridLayout(2,2,1,1));
        setBox();
        for(Box b : box)
            f.add(b);
        f.setSize(500,500);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        f.setVisible(true); 
    }
}

Upvotes: 0

Views: 96

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

First, you don't need to do this...

protected void paintComponent(Graphics g){
    super.paintComponent(g);
    setBackground(color);
}

You never want to change the state of ANY component from within ANY paint method, this will simply cause no end of issues and could bring your program to it's knees as it consumes the CPU cycles...

Second, your Box class's constructor never sets the Box's background color. You don't actually need to maintain a reference to the color value, as the Box, via it's inheriancy, already supports this functionality

public Box(Color color, int boxNumber){
    this.boxNumber = boxNumber;
    setBackground(color);
}

Upvotes: 1

Related Questions