JLabel没有在屏幕上显示图像

时间:2016-04-21 14:35:15

标签: java jlabel imageicon

因此,对于我的项目,我必须使用JLabelImageIcon在屏幕上绘制图形。我做过一些研究,但我似乎无法将它渲染到窗口。它应该渲染20只鸟,每只鸟有不同的位置,但屏幕保持空白。这是类文件:

import javax.swing.*;
import java.awt.*;
import java.io.*;

class Graphics
{
    public static final String SIMULATOR_NAME = "Flocking Simulator 2K16";
    public static final int MAXIMUM_WIDTH = 1280;
    public static final int MAXIMUM_HEIGHT = 780;

    static Canvas canvas = new Canvas();

    private JFrame frame = new JFrame();

    public Graphics()
    {
        JFrame frame = new JFrame();
        frame.setTitle(SIMULATOR_NAME);
        frame.setSize(MAXIMUM_WIDTH, MAXIMUM_HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(canvas);
    }

    public void Clear()
    {
        canvas.clear();
    }

    public void DrawBirds(Flock birds, String graphic)
    {
        for (int i = 0; i < birds.GetMaximumBirds(); i++)
        {
            System.out.printf("Bird#" + i + "\n");
            Bird b = birds.GetBird(i);
            frame.add(BirdGraphic(b, graphic));
        }
    }

    public JLabel BirdGraphic(Bird bird, String graphic)
    {
        System.out.printf(System.getProperty("user.dir") + File.separator + graphic + "\n");
        ImageIcon birdImage = new ImageIcon(System.getProperty("user.dir") + File.separator + graphic);
        JLabel birdLabel = new JLabel(birdImage);
        CartesianCoordinate loc = bird.GetPosition();
        birdLabel.setLocation((int)Math.floor(loc.getX() + 0.5), (int)Math.floor(loc.getY() + 0.5));
        return birdLabel;
    }
}

1 个答案:

答案 0 :(得分:0)

您不能直接在框架中添加标签。您必须将它们添加到必须在框架中的某个面板中。我们也不知道你真正想做什么,你的画布的目的是什么? 也不要混合awt和swing,我的意思是不要使用Canvas,而不是JComponent