将JComponent扩展对象数组添加到JFrame

时间:2018-04-11 09:39:57

标签: java swing jframe jcomponent

我开始使用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]);
        }       
    }
}

问题是它只打印一颗星,我认为它是最后一颗,coords就像他们应该这样做的工作,所以我认为错误是在JComponent或JFrame实现中,我是自我 - 学习,所以也许我的代码不是使用swing的正确方法。

谢谢你,对不起我的英语,我试着把它写得最清楚。

1 个答案:

答案 0 :(得分:1)

在您的情况下,您无法使用布局管理器,需要将其重置为null。请参阅下面的代码

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());
        }
    }
}