简体   繁体   English

向Jframe添加图像

[英]Adding an Image to Jframe

I have an error in the line where I made the catch , and I would like to know how to add an image to the jframe. 在执行catch的行中出现错误,我想知道如何向jframe添加图像。 I've tried a lot things, but I can't make it work, can someone help me please? 我已经尝试了很多东西,但是我无法使它起作用,有人可以帮我吗?

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import  java.io.File;
import java.awt.*;
import java.awt.image.*;

public class Frame extends JFrame {
     private JLabel foto;   
    // private JButton previous, next;
    public Frame() throws Exception{
        super("Colors");
        setLayout(new FlowLayout());

        BufferedImage imagen = null;

        try{
             imagen = ImageIO.read(new File("C:\\Users\\Juan Barrientos\\Desktop\\cuadro.bmp"));
            foto.setIcon(new ImageIcon(imagen));
        }catch(IOException e){  
             foto.setIcon(null);

         }

        // ImageIcon image = new ImageIcon("C:\\Users\\Juan Barrientos\\Desktop\\cuadro.bmp");
        // JLabel foto = new Jlabel(image);
        // add(foto,BorderLayout.CENTER);

       JButton rojo = new JButton ("Rojo");
        add(rojo);
        JButton azul = new JButton ("Azul");
        add(azul);
        JButton verde = new JButton ("Verde");
        add(verde);
        JButton rva = new JButton ("RVA");
        add(rva);
        JButton rav = new JButton ("RAV");
        add(rav);


    }

    public static void main(String[] ar) throws Exception{
        Frame color1=new Frame();
        color1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        color1.setSize(800, 800);
        color1.setBounds(0,0,300,200);
        color1.setResizable(true);
        color1.setVisible(true);
    }
}

It throws a null pointer exception because foto was never instantiated. 因为从未实例化foto ,所以它将引发空指针异常。 Debugging your own code is one of the best ways to learn. 调试自己的代码是学习的最佳方法之一。 However especially for putting finicky graphics you should absolutely find a book or tutorial to follow. 但是,特别是在放置挑剔的图形时,您绝对应该找到一本书或教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM