1

我在制作的行中有错误,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);
    }
}
4

1 回答 1

0

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

于 2013-09-13T01:57:48.973 回答