因此对于我的项目,我必须使用JLabel
和ImageIcon
将图形绘制到屏幕上。我已经做了一些研究,但我似乎无法让它向窗口渲染任何东西。它应该呈现每个20个不同位置的鸟,但屏幕保持空白。这里是类文件:JLabel在屏幕上不显示图像
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;
}
}
检查'new File(System.getProperty(“user.dir”)+ File.separator + graphic).exists()'返回'true'。 – Berger
刚刚检查过它返回'true' – dave
框架如何调用?除了'frame.add(canvas);'我没有看到任何东西被添加到它。另请提供启动您的应用程序的主要方法。 – Berger