0

这是一个任务,所以我宁愿不寻求帮助,但我似乎看不出我做错了什么。代码最终会创建一个窗口,以图像为背景,然后使用文本文件中的信息,将其他图像放置在特定点,用户可以放大。

目前,我只是想将图像显示到 JFrame 内的 JPanel 上,但我似乎无法让它工作。有人可以指出我正在做什么导致图像不显示吗?

地图类代码:

import javax.swing.*;

public class Map extends JPanel
{   
    static final long serialVersionUID = 1;

public Map()
{
}

public JPanel createContentPane()
{
    //Creating a base JPanel to place everything on
    JPanel rootGUI = new JPanel();
    //Setting the Layout Manager to null to place everything manually
    rootGUI.setLayout(null);
    rootGUI.setOpaque(true);
    return rootGUI;
}

private static void createAndShowGUI()
{
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Test for image");
    //Create and set up the content pane
    Map demo = new Map();
    frame.setContentPane(demo.createContentPane());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setResizable(false);
    Hospital hDemo = new Hospital();
    frame.add(hDemo);
    frame.setVisible(true);
}

public static void main(String[] Args)
{
    //Schedule a job for the event-dispatching thread
    //Creating and showing this applications GUI
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            createAndShowGUI();
        }
    });
}
}

和医院类的代码:

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

public class Hospital extends JPanel
{
static final long serialVersionUID = 2;
public static BufferedImage hospitalImage;

public Hospital()
{
    super();
    try
    {
        hospitalImage = ImageIO.read(new File("src\\hospital.jpg"));
    }
    catch (IOException ex)
    {
        //Not handled
    }
}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.drawImage(hospitalImage, 50, 50, this);
    repaint();
}
}
4

2 回答 2

0

You haven't defined the size of your Hospital Panel.

update to:

public Hospital()
{
    super();
    setSize( /* size */ );
    try
    {
        hospitalImage = ImageIO.read(new File("src\\hospital.jpg"));
    }
    catch (IOException ex)
    {
        //Not handled
    }
}

or use a different layoutManager in your JFrame/ContentPane like Borderlayout

in that case you could add the Hospital to your Frame as

frame.add(hDemo, BorderLayout.CENTER);

visual guide to layoutmanagers

于 2013-08-14T11:40:13.023 回答
0

Problem is in path you are passing here: hospitalImage = ImageIO.read(new File("src\\hospital.jpg"));

Easy solution would be to load your image as a stream:

InputStream stream = getClass().getResourceAsStream("hospital.jpg");
hospitalImage = ImageIO.read(stream);
stream.close();
于 2013-08-14T12:00:51.053 回答