Add image to JPanel within JLabel

1.4k views Asked by At

I have this code:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;

    public class Interface {

        private JPanel panel;
        private JPanel buttonPane;
        private JLabel label;
        private JLabel label2;
        private JTextField textfield;
        private JTextField textfield2;
        private JTextField textfield3;
        private JTextField textfield4;
        private JTextField textfield5;
        private JButton button;
        private JButton button2;
        private JButton button3;
        private JButton button4;
        private JButton button5;
        private JButton button6;

        public static void main(String[] args) {
            new Interface();
        }

        public Interface() {
            JFrame frame = new JFrame("Vormen");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(600, 300);
            frame.setLocationRelativeTo(null);

            panel = new JPanel();
            buttonPane = new JPanel();
            button = new JButton("cirkel");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {     
    JLabel label3 = new JLabel(new ImageIcon("images/cirkel.png"));
            panel.add(label3);
            panel.revalidate();
            panel.repaint();
        buttonPane.add(button);
        buttonPane.add(button2);
        buttonPane.add(button3);


        frame.add(buttonPane, BorderLayout.NORTH);
        frame.add(panel);
        frame.setVisible(true);

    }
}

However, if I run it, the image doesn't appear.

Why is that? I'm new to Java so I make little mistakes like this very easily.

I have tried several options but none of them worked out for me.

1

There are 1 answers

4
camickr On
JLabel label3 = new JLabel(new ImageIcon("/images/cirkel.png"));

Don't use /images/.... The leading "/" tells java to look at the root directory of your drive.

I'm guessing your "images" directory is in your source directory so you should be using:

JLabel label3 = new JLabel(new ImageIcon("images/cirkel.png"));

I'm new to Java so I make little mistakes like this very easily.

Read the Swing tutorial on How to Use Icons for better examples of how to load images and working examples to give you a better structure to your program.

The idea is to start with a working program and learn from the structure of that program. Then make small changes. If it stops working then you know what you changed and what caused the problem.