Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [JAVA] Promblemi nel caricare e visualizzare un'immagine

    Ciao a tutti, sono un principiante di java e di programmazione in generale.
    Sto facendo un un'applicazione nella quale devo caricare una immagine scegliendola con il filechooser e visualizzarla all'interno del pannello centrale. Quello che ho scritto...o meglio ho fatto qualche copia e incolla quà e là...mi visualizza l'immagine ma non riesce a centrarla correttamente..La mia idea era quella di creare una JLabel e caricare all'interno una ImageIcon che contenesse l' immagine da me scelta con il filechooser(in questo modo risolvevo il problema di ridimensionamento dell' immagine:lo fa in automatico): ed è quello che ho fatto. Purtroppo per me però non riesco a visualizzarla correttamente...

    Vi scrivo il codice che ho fatto...
    Spero qualcuno mi risonda...




    codice:
    package it.testimage;
    
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    
    import javax.swing.BorderFactory;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SpringLayout;
    import javax.swing.border.Border;
    
    
    public class JFrameExample extends JFrame 
    {
    	
    	String JFbanner="Simpatico";
    	
    	public JFrameExample() {
    		//super(title);
            setTitle(JFbanner);
            //componente centrale
            JLabel labelIcon = new JLabel(new ImageIcon("C:/inverno.jpg"));
            labelIcon.setBorder(BorderFactory.createLineBorder(Color.black));
    
            //componente nord e sud
            JTextField northtextField = new JTextField("Premi OK");
            JTextField southtextField = new JTextField("Premi OK");
            northtextField.setEditable(false);
            southtextField.setEditable(false);
            
    //      Pannello NORTH
            JPanel northPanel = new JPanel();
            northPanel.setLayout(new GridLayout(1,0));
            northPanel.setBorder(BorderFactory.createEmptyBorder(10,4,10,4));
            northPanel.add(northtextField);
            
            // Pannello CENTER
            centralPanel = new JPanel();
            centralPanel.setLayout(new BorderLayout());
            centralPanel.setBorder(
                BorderFactory.createEmptyBorder(3,4,3,4));
            centralPanel.add(BorderLayout.CENTER,labelIcon);
    
            //Pannello EAST
            JPanel eastPanel=new JPanel();
           // eastPanel.setLayout(new BorderLayout());
            
            
            // Pannello SOUTH
            JPanel southPanel = new JPanel();
            southPanel.setLayout(new GridLayout(0,1));
            southPanel.setBorder(BorderFactory.createEmptyBorder(10,4,10,4));
            southPanel.add(southtextField);
            
            
            JButton selectImageButton = new JButton("Select Image");
            selectImageButton.setPreferredSize(new Dimension(110, 20));
            selectImageButton.addActionListener(new ActionListener()
            		{
                public void actionPerformed(ActionEvent e) 
                		{
                    		JFileChooser fc = new JFileChooser();
                    		fc.addChoosableFileFilter(new ImageFilter());
                    		fc.setFileView(new ImageFileView());
                    		fc.setAccessory(new ImagePreview(fc));
                    		int returnVal = fc.showDialog(JFrameExample.this, "Select Image");
                    		if(returnVal==JFileChooser.APPROVE_OPTION)
                    		{
                    		if (fc.getSelectedFile() == null)
                    		{ return; }
                    		File file=fc.getSelectedFile();
                    		String path=(String)file.getPath();
                    		loadImage(path);
                    		}
                		}
            		});
                          
            JButton selectFocusButton = new JButton("Select Focus");
            selectFocusButton.setPreferredSize(new Dimension(110, 20));
            JButton selectPointsButton = new JButton("Select Points" );
            selectPointsButton.setPreferredSize(new Dimension(112, 20));
            SpringLayout layout = new SpringLayout();
            
            
          //  center.setLayout(layout);
            //nter.add(immagine);
            eastPanel.setLayout(layout);
            eastPanel.add(selectImageButton);
            eastPanel.add(selectFocusButton);
            eastPanel.add(selectPointsButton);
            
            layout.putConstraint(SpringLayout.NORTH,  selectImageButton,    3, SpringLayout.NORTH,  northPanel);
            layout.putConstraint(SpringLayout.NORTH,  selectFocusButton,   10, SpringLayout.SOUTH,  selectImageButton);
            layout.putConstraint(SpringLayout.NORTH,  selectPointsButton,  10, SpringLayout.SOUTH,  selectFocusButton);
            layout.putConstraint(SpringLayout.EAST,   eastPanel,          5, SpringLayout.EAST,   selectFocusButton);
            layout.putConstraint(SpringLayout.EAST,   eastPanel,           5, SpringLayout.EAST,   selectImageButton);
            //layout.putConstraint(SpringLayout.EAST,   selectImageButton,   10, SpringLayout.WEST,   eastPanel);
            //layout.putConstraint(SpringLayout.EAST, centralPanel,               20, SpringLayout.EAST,   eastPanel);
            
           
              
              JFrame f = new JFrame(JFbanner);
              f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              f.getContentPane().setLayout(new BorderLayout());
              f.getContentPane().add(BorderLayout.NORTH,northPanel);
              f.getContentPane().add(BorderLayout.CENTER,centralPanel);
              f.getContentPane().add(BorderLayout.SOUTH,southPanel);
              f.getContentPane().add(BorderLayout.EAST,eastPanel);
              f.pack();
              f.setVisible(true);
            
    	}
    	
    	public JPanel centralPanel;
    	public BufferedImage mBufferedImage;	
    	
    	public void loadImage(String fileName)
    	{
    		Image image = Toolkit.getDefaultToolkit().getImage(fileName);
    		MediaTracker mt = new MediaTracker(this);
    		mt.addImage(image, 0);
    		try { mt.waitForID(0); }
    		catch (InterruptedException ie) { return; }
    		if (mt.isErrorID(0)) return;
    	
    //		mBufferedImage = new BufferedImage(image.getWidth(null),
    //		image.getHeight(null),
    //		BufferedImage.TYPE_INT_RGB);
    		Graphics g = centralPanel.getGraphics();
    		g.drawImage(image, 0, 0, null);
    	
    		validate();
    		repaint();
    		setTitle(JFbanner + ": " + fileName);
    	}
    	
    	public void paint(Graphics g)
    	{
    	super.paint(g);
    	if (mBufferedImage == null) return;
    	Insets insets = getInsets();
    	g.drawImage(mBufferedImage, insets.left, insets.top, this);
    	}
    
    	public static void main(String[] args) 
    	{
    		
    		 JFrameExample ex=new JFrameExample();
    		 //ex.setSize(500,300);
    		 //ex.show();
    	}
    
    
    }
    
    
    
    
    
    
    package it.testimage;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    
    public class ImageFileView extends FileView {
        ImageIcon jpgIcon = new ImageIcon("images/jpgIcon.gif");
        ImageIcon gifIcon = new ImageIcon("images/gifIcon.gif");
        ImageIcon tiffIcon = new ImageIcon("images/tiffIcon.gif");
        
        public String getName(File f) {
            return null; // let the L&F FileView figure this out
        }
        
        public String getDescription(File f) {
            return null; // let the L&F FileView figure this out
        }
        
        public Boolean isTraversable(File f) {
            return null; // let the L&F FileView figure this out
        }
        
        public String getTypeDescription(File f) {
            String extension = getExtension(f);
            String type = null;
    
            if (extension != null) {
                if (extension.equals("jpeg") ||
                    extension.equals("jpg")) {
                    type = "JPEG Image";
                } else if (extension.equals("gif")){
                    type = "GIF Image";
                } else if (extension.equals("tiff") ||
                           extension.equals("tif")) {
                    type = "TIFF Image";
                } 
            }
            return type;
        }
        
        public Icon getIcon(File f) {
            String extension = getExtension(f);
            Icon icon = null;
            if (extension != null) {
                if (extension.equals("jpeg") ||
                    extension.equals("jpg")) {
                    icon = jpgIcon;
                } else if (extension.equals("gif")) {
                    icon = gifIcon;
                } else if (extension.equals("tiff") ||
                           extension.equals("tif")) {
                    icon = tiffIcon;
                } 
            }
            return icon;
        }
        
        // Get the extension of this file. Code is factored out
        // because we use this in both getIcon and getTypeDescription
        private String getExtension(File f) {
    
            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');
    
            if (i > 0 &&  i < s.length() - 1) {
                ext = s.substring(i+1).toLowerCase();
            }
            return ext;
        }
    }
    
    
    
    
    package it.testimage;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    
    public class ImageFilter extends FileFilter {
        final static String jpeg = "jpeg";
        final static String jpg = "jpg";
        final static String gif = "gif";
        final static String tiff = "tiff";
        final static String tif = "tif";
        
        // Accept all directories and all gif, jpg, or tiff files.
        public boolean accept(File f) {
    
            if (f.isDirectory()) {
                return true;
            }
    
            String s = f.getName();
            int i = s.lastIndexOf('.');
    
            if (i > 0 &&  i < s.length() - 1) {
                String extension = s.substring(i+1).toLowerCase();
                if (tiff.equals(extension) ||
                    tif.equals(extension) ||
                    gif.equals(extension) ||
                    jpeg.equals(extension) ||
                    jpg.equals(extension)) {
                        return true;
                } else {
                    return false;
                }
            }
    
            return false;
        }
        
        // The description of this filter
        public String getDescription() {
            return "Just Images";
        }
    }
    
    
    
    
    
    package it.testimage;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import java.io.File;
    
    public class ImagePreview extends JComponent 
                              implements PropertyChangeListener {
        ImageIcon thumbnail = null;
        File file = null;
                                 
        public ImagePreview(JFileChooser fc) {
            setPreferredSize(new Dimension(100, 50));
            fc.addPropertyChangeListener(this);
        }
    
        public void loadImage() {
            if (file == null)
                return;
     
            ImageIcon tmpIcon = new ImageIcon(file.getPath());
            if (tmpIcon.getIconWidth() > 90) {
                thumbnail = new ImageIcon(tmpIcon.getImage().
                                          getScaledInstance(90, -1,
                                                            Image.SCALE_DEFAULT));
            } else {
                thumbnail = tmpIcon;
            }
        }
    
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();
            if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                file = (File) e.getNewValue();
                if (isShowing()) {
                    loadImage();
                    repaint();
                }
            }
        }
    
        public void paintComponent(Graphics g) {
            if (thumbnail == null) {
                loadImage();
            }
            if (thumbnail != null) {
                int x = getWidth()/2 - thumbnail.getIconWidth()/2;
                int y = getHeight()/2 - thumbnail.getIconHeight()/2;
    
                if (y < 0) {
                    y = 0;
                }
    
                if (x < 5) {
                    x = 5;
                }
                thumbnail.paintIcon(this, g, x, y);
            }
        }
    }


    Spero di non essere stato troppo confuso.

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    ti dico la verità che tutto quel codice non l'ho nemmeno provato ...
    Questo va però... vedi se magari riesci a tirarne fuori qualcosa di utile anche per la tua applicazione.

    codice:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    
    
    public class displayImages extends JFrame implements ActionListener {
      
      
      File f;
      JLabel img;
      JScrollPane sc;
      
      private ImageIcon createImageIcon(String path) {
        try {
          
           return new ImageIcon(path);
        }
        catch (Exception e) {
          System.out.println(e.toString());
          return null;
        }
      }
    
      
      public void actionPerformed (ActionEvent ae) {
        try {
          JFileChooser fc = new JFileChooser();
          fc.showDialog(this, "Choose Image");
          f = fc.getSelectedFile();
          try {
            img.setVisible(false);
            sc.setVisible(false);
          }
          catch (Exception ex) {}
          img = new JLabel(createImageIcon(f.getAbsolutePath()));
          sc = new JScrollPane(img);
          this.getContentPane().add(sc, BorderLayout.CENTER);
          this.validate();
        }
        catch (Exception e) {}
      }
      
      public displayImages() {
        super("Image display");
        JButton open = new JButton("Open...");
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(open, BorderLayout.NORTH);
        open.addActionListener(this);
        this.setSize(300, 300);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      }
      
      public static void main (String[] args) {
        displayImages d = new displayImages();
      }
    }
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  3. #3

    Grazie

    Grazie Andrea1979 mi sei stato molto utile...

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.