Search code examples
eclipseimagejpegjlabelphoto

displaying jpg to a jPanel


So i am trying to add an image to my program after a button is pressed with a certain value entered into a text field. I want the image to be blank until the button is pressed with the correct value. The only issue i seem to be having is making the photo appear, i know the output should be working. here is the code i have for adding the label.

photo = new JLabel();
photo.setBounds(425, 170, 400, 360);
contentPane.add(photo);
ImageIcon icon = new ImageIcon("AwsomeSauce.jpg");

here is the code for when the value is entered correctly

if (error) {
    photo.setIcon(image);
  }

now im still pretty new at this so go easy on me.


Solution

  • Here is simple example for you:

    public class Frame extends JFrame {
    
        private JLabel label;
    
        public Frame() {
            getContentPane().add(label = new JLabel(),BorderLayout.SOUTH);
            JButton b = new JButton("show Icon");
            b.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    URL resource = getClass().getResource("/res/3_disc.png");
                    ImageIcon ico = new ImageIcon(resource);
                    label.setIcon(ico);
                }
            });
            getContentPane().add(b,BorderLayout.NORTH);
        }
    
        public static void main(String[] args) {
            Frame frame = new Frame();    
            frame.setTitle("This is a test");
            frame.setSize(300, 300);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);    
        }
    }
    

    "/res/3_disc.png" - is my icon which is placed in my project in res folder.