user3275944
user3275944

Reputation: 57

Icon in Java - how to add icon in a panel

Refer to this link to see the image: https://www.dropbox.com/s/byeah81vg1cck5m/output.jpg I want a panel like the picture above. hello , i am a beginner on Java , i would like to know how is it possible to add this icon within a panel with the scrollbar . I have tried with JLabel, here is my code:

      JPanel panel = new JPanel();
    panel.setLayout(null);
    JScrollPane txtstmtPane = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    ImageIcon icon=new ImageIcon ( "icon/filter.jpg" );
    JLabel label = new JLabel();
    label.setIcon(icon);
    label.setBounds(600, 600, 40, 30);
    panel.add(label);
    txtstmtPane.setViewportView(panel);
    add(txtstmtPane);

Upvotes: 1

Views: 1367

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

See this:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImagePanel extends JPanel{
    private BufferedImage bi;

    public ImagePanel() {  

      try {
            bi = ImageIO.read(new File("Your Image Path"));
        } catch (IOException ex) {
            Logger.getLogger(ImagePanel.class.getName()).log(Level.SEVERE, null, ex);
        }


        final JPanel panel = new JPanel(){
            @Override
            protected void paintComponent(Graphics g){
                Graphics g2 = g.create();
                g2.drawImage(bi, 0, 0, getWidth(), getHeight(), null);
                g2.dispose();
            }

            @Override
            public Dimension getPreferredSize(){
                return new Dimension(bi.getWidth()/2, bi.getHeight()/2);
                //return new Dimension(200, 200);
            }
        };

        add(panel);
    }  

        public static void main(String args[]){
            SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ImagePanel imgPanel=new ImagePanel();
                JOptionPane.showMessageDialog(
                        null, imgPanel, "Image Panel", JOptionPane.PLAIN_MESSAGE);
            }
        });
        }
}

Output

output


Tips

  1. Don't use NULL layout (as @camickr suggested)
  2. Use proper Layout Manager
  3. Using this code I don't thing you need ScrollPane

Upvotes: 2

camickr
camickr

Reputation: 324078

Don't use null layouts!!!

A scrollpane will only work when the preferred size of the component added to the viewport is greater than the size of the viewport.

You can just add the label directly to the scrollpane, you don't need to add it to the panel first.

Upvotes: 1

Related Questions