我究竟做错了什么? Java将图像绘制到JPanel

时间:2013-08-14 11:26:33

标签: java swing jframe jpanel paintcomponent

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

目前我只是试图将图像显示在JFrame内的JPanel上,而我似乎无法让它工作。有人可以指出我究竟在做什么导致图像无法显示?

Map类代码:

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

2 个答案:

答案 0 :(得分:0)

您尚未定义医院面板的大小。

更新至:

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

或在JFrame / ContentPane中使用不同的layoutManager,例如Borderlayout

在这种情况下,您可以将医院添加到您的框架

frame.add(hDemo, BorderLayout.CENTER);

visual guide to layoutmanagers

答案 1 :(得分:0)

问题在于您在此处传递的路径:hospitalImage = ImageIO.read(new File("src\\hospital.jpg"));

简单的解决方案是将图像加载为流:

InputStream stream = getClass().getResourceAsStream("hospital.jpg");
hospitalImage = ImageIO.read(stream);
stream.close();