java - 线程中的异常 "AWT-EventQueue-0"java.lang.IllegalArgumentException : input == null

标签 java swing exception

我想在单击按钮时在此程序中显示随机图像,但出现异常错误并且无法修复它。

public class TestImage1 {

    public static void main(String args[]) throws IOException {
        String sonido = "Windows Navigation Start.wav";
        InputStream in = new FileInputStream(sonido);
        AudioStream audio = new AudioStream(in);
        AudioPlayer.player.start(audio);
        try {
            TestImage1 obj = new TestImage1();
            obj.run(args);
        } catch (Exception e) {
        }
    }

    public void run(String[] args) throws Exception {
        imgRandom form = new imgRandom();
        form.setBounds(0, 0, 500, 400);
        form.setVisible(true);
    }

    public class imgRandom extends JFrame implements ActionListener {

        private JLabel label2;
        JButton boton;
        String cads[] = {"/img/duck.gif", "/img/luigi.png", "/img/mario.jpg"};

        public imgRandom() throws IOException {
            setLayout(null);
            label2 = new JLabel("press");
            label2.setBounds(10, 20, 100, 100);
            add(label2);

            boton = new JButton("Presioname!!");
            boton.setBounds(150, 250, 200, 100);
            add(boton);
            boton.addActionListener(this);

        }

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == boton) {
                int ra = (int) (Math.random() * 3);
                URL url = this.getClass().getResource(cads[ra]);
                try {
                    Image img = ImageIO.read(url);
                    label2.setIcon(new ImageIcon(img));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }
    }
}

松贝迪可以告诉我如何修复它吗?如果按下按钮,它应该显示随机图像,但会引发异常并出现许多其他错误。

最佳答案

在您的代码中,获取图像时可能会出现一些问题。

我已经在相同的上下文中发布了一些可能对您有帮助的答案。

<小时/>

一些要点:

  1. 不要使用 null 布局,而是使用正确的布局,这就是它们的设计目的。

    了解更多 How to Use Various Layout Managers

  2. 使用 SwingUtilities.invokeLater() 确保 EDT已正确初始化。

    了解更多

  3. 除非您要修改现有逻辑,否则不要扩展任何类。

    了解更多

关于java - 线程中的异常 "AWT-EventQueue-0"java.lang.IllegalArgumentException : input == null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24188752/

相关文章:

java - 如果 try block 突然完成怎么办?

java - 如何在不刷新整个 Pane 的情况下附加到 JEditorPane?

java - 以图像为背景的 Jbutton 无法单击

java - 应用程序启动时图像超出 imageview

java - JIRA 是否支持 Tomcat 8?

java - JGraphX 图形未显示在 JPanel 中

vb.net - 函数调用自身,无法避免 StackOverflow 错误

c# - 仅在 Release 中 try catch 的更好方法?

java - 出现错误 : Error parsing system bundle export statement when loading Fuse ESB

java - 不同的 (HotSpot) JVM 线程类型有什么作用?