如何将BufferedImage绘制到JFrame上

时间:2015-12-23 18:39:45

标签: java swing jframe png bufferedimage

所以我编写的代码应该是一个名为text2.png的已保存的png图像,并将其绘制在JFrame中。这是我的代码:

public class TrainFromData extends JComponent{
    public void train(String fileName) throws Exception
    {
        try
        {
            File file = new File(fileName);
            BufferedImage img = ImageIO.read(file);
            Graphics2D g2d = img.createGraphics();
            g2d.drawImage(img, 50, 50, 150, 150, null);
            paint(g2d);
            g2d.dispose();
        }

        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
    public void paint(Graphics g)
    {
        super.paint(g);
    }

    public static void main(String[] args) throws Exception {
        JFrame testFrame = new JFrame();
        testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        final TrainFromData comp = new TrainFromData();
        comp.setPreferredSize(new Dimension(320, 200));
        testFrame.getContentPane().add(comp, BorderLayout.CENTER);
        testFrame.pack();
        testFrame.setVisible(true);
        comp.train("text2.png");
    }
}

我的代码只是绘制一个空的JFrame,我无法弄清楚如何让它自己绘制图像。谢谢!

2 个答案:

答案 0 :(得分:1)

  

如何将BufferedImage绘制到JFrame

无需自定义绘画。

只需使用JLabel即可显示图像。

BufferedImage img = ImageIO.read(file);
JLabel label = new JLabel( new ImageIcon(img) );
...
testFrame.add(label, BorderLayout.CENTER);

答案 1 :(得分:0)

您的代码不应直接调用您的paint方法。相反,你应该调用repaint()。然后,窗口工具包将使用适当的Graphics对象调用paint方法。你应该画进那个对象。将BufferedImage定义为实例变量。你可以做这样的事情:

public class TrainFromData extends Component{
    BufferedImage img;
    public void train(String fileName) throws Exception
    {
        try
        {
             File file = new File(fileName);
             img = ImageIO.read(file);
             repaint();  
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
    @Override
    public void paintComponent(Graphics g) //instead of paint()
    {
        super.paintComponent(g);
        if ( img != null )
             g.drawImage(img, 50, 50, 150, 150, null);
    } 
    //etc.