簡體   English   中英

線程“ AWT-EventQueue-0”中的異常java.lang.IllegalArgumentException:輸入== null

[英]Exception in thread “AWT-EventQueue-0” java.lang.IllegalArgumentException: input == null

單擊按鈕時,我想在此程序中顯示隨機圖像,但出現異常錯誤,無法修復。

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布局,而要使用正確的布局,這就是為什么要為其設計的原因。

    閱讀更多信息如何使用各種布局管理器

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

    閱讀更多

  3. 除非修改現有邏輯,否則不要擴展任何類。

    閱讀更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM