0

I want to display a random image in this program when the button is clicked but i get an exception error and cant fix it.

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

            }
        }
    }
}

can sombedy tell me how to fix it. if the button is pressed it should display a random image but it throws an exception with a lot of other error.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

1 Answers1

2

In your code there might be some issues while getting the images.

I have already posted some answers in the same context that might help you.


Some points:

  1. Don't use null layout instead use proper layout that's why they are designed for.

    Read more How to Use Various Layout Managers

  2. Use SwingUtilities.invokeLater() to make sure that EDT is initialized properly.

    Read more

  3. Don't extend any class until and unless you are modifying the existing logic.

    Read more

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • +1, `In your code there might be some issues while getting the images.` - the code works fine for me, so would also guess this is the problem. – camickr Jun 12 '14 at 17:14