gpt4 book ai didi

java - 添加对象时 ContentPane 背景颜色发生变化

转载 作者:行者123 更新时间:2023-12-02 06:26:27 25 4
gpt4 key购买 nike

我有以下代码:

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);.我想要的是一个粉红色的球在黑色背景上弹跳,但添加球时它会一直变回灰色。

问题是什么?

最佳答案

JPanel 扩展的

Ball 是不透明的(看不透),因此它用默认颜色填充自己的背景...

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

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

关于java - 添加对象时 ContentPane 背景颜色发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20483770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com