【问题标题】:Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null线程“AWT-EventQueue-0”java.lang.IllegalArgumentException 中的异常:输入 == null
【发布时间】:2014-06-12 15:52:17
【问题描述】:

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

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();
                }

            }
        }
    }
}

能否告诉我如何解决它。如果按下按钮,它应该会显示一个随机图像,但它会引发异常并引发许多其他错误。

【问题讨论】:

  • setLayout(null);你为什么这样做?

标签: java swing exception


【解决方案1】:

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

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


几点:

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

    阅读更多How to Use Various Layout Managers

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

    阅读全文

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

    阅读全文

【讨论】:

  • +1, In your code there might be some issues while getting the images. - 代码对我来说很好,所以也猜这是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
相关资源
最近更新 更多