添加对象时,ContentPane背景颜色会发生变化

时间:2013-12-10 00:32:55

标签: java swing

我有以下代码:

import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class Ball extends JPanel implements Runnable {

    List<Ball> balls = new ArrayList<Ball>();   
    Color color;
    int diameter;
    long delay;
    private int x;
    private int y;
    private int vx;
    private int vy;

    public Ball(String ballcolor, int xvelocity, int yvelocity) {
        color = Color.PINK;
        diameter = 30;
        delay = 40;
        x = 1;
        y = 1;
        vx = xvelocity;
        vy = yvelocity;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(color);
        g.fillOval(x,y,50,50); //adds color to circle
        g.setColor(Color.pink);
        g2.drawOval(x,y,50,50); //draws circle
    }

    public void run() {
        while(isVisible()) {
            try {
                Thread.sleep(delay);
            } catch(InterruptedException e) {
                System.out.println("interrupted");
            }
            move();
            repaint();
        }
    }

    public void move() {
        if(x + vx < 0 || x + diameter + vx > getWidth()) {
            vx *= -1;
        }
        if(y + vy < 0 || y + diameter + vy > getHeight()) {
            vy *= -1;
        }
        x += vx;
        y += vy;
    }

    private void start() {
        while(!isVisible()) {
            try {
                Thread.sleep(25);
            } catch(InterruptedException e) {
                System.exit(1);
            }
        }
        Thread thread = new Thread(this);
        thread.setPriority(Thread.NORM_PRIORITY);
        thread.start();
    }

    public static void main(String[] args) {
        Ball ball1 = new Ball("pink",6,6);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setBackground(Color.BLACK);
        f.getContentPane().add(ball1);
        f.setSize(1000,500);
        f.setLocation(200,200);
        new Thread(ball1).start();
        f.setVisible(true);
    }
}

我想将背景设为黑色而不是默认的灰色背景,但这只有在我从代码中取出球时才有效,基本上是删除f.getContentPane().add(ball1);。我想要的是一个粉红色的球在黑色背景上弹跳,但在加入球时它会一直变回灰色。

有什么问题?

1 个答案:

答案 0 :(得分:2)

Ball延伸的

JPanel是不透明的(不透视),所以它用它的默认颜色填充它自己的背景......

您可以使用Ball使setOpaque(false)透明,或使用BallBLACK的背景颜色设置为setBackground(Color.BLACK),例如...

ps-我应该添加,因为JFrame使用BorderLayout,您的Ball窗格将占据框架中心的整个可用空间(CENTER是默认位置和不包含任何其他组件的框架)