ImageIO异常无法读取我的输入文件。对于读取文件时的缓冲图像

时间:2013-12-14 22:45:56

标签: java image

public FinalProject() throws IOException
     {
        String fontType = JOptionPane.showInputDialog("What kind of font would you like? "); 
        String backgroundColor = JOptionPane.showInputDialog("Would you like your background color to be blue, green or pink?");
        if(backgroundColor.equals("blue"))
        {
            setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad.png")));
        }
        else if(backgroundColor.equals("pink"))
        {
            setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad2.png")));
        }
         else if(backgroundColor.equals("green"))
        {
            setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad3.png")));
        }
        else
        {
            JOptionPane.showMessageDialog(c, "Sorry color not recognized so color was set to the defalut (blue)");
            setContentPane(new JLabel(new ImageIcon("calculator_back_and_keypad.png")));
        }
        Font font = new Font(fontType, Font.BOLD, 30);
        txt = new JTextField(13); //create a text field
        Color color = new Color(255,0,0);
        txt.setForeground(color);
        txt.setFont(font);
        c = getContentPane();

        setLayout(new FlowLayout());
        c.add(txt);

        buttons = new HashMap <String, JButton>();

        String[] names = {"1","2","3","4","5","6","7","8","9","0","+","-","x","/","sin","cos","tan","arcsin","arccos","arctan","log","abs","sqrt","exp","M","M Recall","C","="};
        for (String d: names)
        {
            BufferedImage pic1 = ImageIO.read(new File("button1.jpg"));
            JButton i = new JButton(new ImageIcon(pic1));
            i.setPreferredSize(new Dimension(75,75));
            c.add(i);
            i.addActionListener(this);
            buttons.put(d, i);
        }

?ImageIO说它无法读取文件,文件在文件夹内 了。
            的setSize(400650);             调用setVisible(真);             的setResizable(假);             txt.setEditable(假);

1 个答案:

答案 0 :(得分:0)

从评论中我认为你必须使用ImageIO.#read(URL)方法。另外你为什么在for循环中做同样的事情?

URL url = this.getClass().getResource("/path/to/resource/button1.jpg");
BufferedImage pic1 = ImageIO.read(url);
JButton i = new JButton(new ImageIcon(pic1));
i.setPreferredSize(new Dimension(75,75));
c.add(i);
i.addActionListener(this);

这应该在for循环之外和for循环中完成

String[] names = {"1","2","3","4","5","6","7","8","9","0","+","-","x","/","sin","cos","tan","arcsin","arccos","arctan","log","abs","sqrt","exp","M","M Recall","C","="};
for (String d : names)
{
    buttons.put(d, i);
}