我从 JFrame 开始,我正在尝试制作 StarField,目前我将 Star JComponent 添加到 Starfield JFrame:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Star extends JComponent{
public int x;
public int y;
private final Color color = Color.YELLOW;
public Star(int x, int y) {
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillOval(x, y, 8, 8);
}
}
和 StarField 代码:
import javax.swing.*;
public class StarField extends JFrame{
public int size = 400;
public Star[] stars = new Star[50];
public static void main(String[] args) {
StarField field = new StarField();
field.setVisible(true);
}
public StarField() {
this.setSize(size, size);
for (int i= 0; i< stars.length; i++) {
int x = (int)(Math.random()*size);
int y = (int)(Math.random()*size);
stars[i] = new Star(x,y);
this.add(stars[i]);
}
}
}
问题在于它只打印一颗星,我认为这是最后一颗星,坐标的工作方式就像他们应该做的那样,所以我认为错误出在 JComponent 或 JFrame 实现中,我自己-学习,所以也许我的代码不是使用 swing 的正确方法。
谢谢你,对我的英语感到抱歉,我尽力写出我所知道的最好的东西。
最佳答案
在您的情况下,您无法使用布局管理器,需要将其重置为空。请参阅下面我的代码
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class StarField extends JFrame {
public int size = 400;
public Star[] stars = new Star[50];
public static void main(String[] args) {
StarField field = new StarField();
field.setVisible(true);
}
public StarField() {
this.setSize(size, size);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// usually you should use a normal layout manager, but for your task we need null
getContentPane().setLayout(null);
for (int i = 0; i < stars.length; i++) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
stars[i] = new Star(x, y);
this.add(stars[i]);
}
}
public class Star extends JComponent {
private final Color color = Color.YELLOW;
public Star(int x, int y) {
// need to set the correct coordinates
setBounds(x, y, 8, 8);
}
@Override
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillOval(0, 0, getWidth(), getHeight());
}
}
}
关于java - 将 JComponent 扩展对象数组添加到 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771651/