将图像添加到Jframe

时间:2013-09-13 00:22:20

标签: java swing jframe jlabel

我在制作catch的行中出错,我想知道如何将图像添加到jframe中。我尝试了很多东西,但我不能让它发挥作用,有人可以帮助我吗?

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

1 个答案:

答案 0 :(得分:0)

它抛出空指针异常,因为foto从未实例化过。调试自己的代码是最好的学习方法之一。然而,特别是对于放置挑剔的图形,你绝对应该找到一本书或教程。