简体   繁体   English

如何在Java中重画

[英]How to repaint in Java

I'm taking a course in GUI programing. 我正在学习GUI编程课程。 I'm having a hard time understanding how to use the repaint my Box class to a different color. 我很难理解如何将Box类重新绘制为其他颜色。 Here is my GUI class: 这是我的GUI类:

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 : 这是我将其添加到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); 
    }
}

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... 您永远都不想在ANY绘制方法中更改ANY组件的状态,这只会导致问题无止境,并且可能会因为消耗CPU周期而使您的程序陷于瘫痪...

Second, your Box class's constructor never sets the Box 's background color. 其次,您的Box类的构造函数从不设置Box的背景色。 You don't actually need to maintain a reference to the color value, as the Box , via it's inheriancy, already supports this functionality 实际上,您不需要维护对颜色值的引用,因为Box通过其继承性已经支持此功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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