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


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 说它无法读取文件,并且文件在文件夹中已经。
套装大小(400,650(; setVisible(true(; setRessizeable(false(; txt.setEditable(false(;

从评论中,我认为您必须使用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);
}

最新更新