Przesuwanie obrazka

0

Witam
Napisałem applet ( jest on pod adresem http://pstawik.republika.pl/viewer/ ) i chciałbym po powiększeniu obrazka móc go przesuwać wewnątrz JScrollPane. Spędziłem już sporo czasu na szukaniu rozwiązania (wiem, że pozycjonowanie pewnie trzeba uzależnić od MouseMotionListener) jednak jestem jużbezradny [glowa]

Kod appletu jest poniżej:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.Color;

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;

import java.util.ArrayList;

public class ImageViewer extends JApplet 
						 implements ActionListener, MouseMotionListener 
{
	private static final int widthConst = 450; //650
	private static final int heightConst = 350; //450
	
	private int width, height; // szerokość i wysokość aktualnie wyświetlanego zdjęcia
	private int i =-1; //nr bieżący
    private int numberOfFotos = 0; //liczba zdjęć w pliku xml
    private int x=0,y=0; // pozycjonowanie obrazka 
        
    private Color backgroundColor = new Color(0,46,184);
    private Color panelBarBackgroundColor = new Color(229,244,255);    
    private Color buttonBarBackgroundColor = new Color(202,232,255);
   
   	private ArrayList<String> fotoNames; // tablica z nazwami plików odczytanymi z pliku xml
    private Image fotos[];
   	private Image obraz[] = new Image [9];   	
   	
  	private JLabel header, tlo, pasekTop, pasekBottom;
   	private JScrollPane scrollPane; 
    private JButton buttonNext, buttonBack, buttonFirst, buttonEnd;  
    private JButton buttonZoomIn, buttonZoomOut, buttonZoomOriginal;  
    private JToggleButton buttonAuto;   
       
        
    /**
  	 *Funkcja inicjująca skalę aktualnego zdjęcia
  	 */
  	public void scaleInit()
	{
		width = widthConst; 
		height = heightConst;
	}	
     
    /**
     *Inicjalizacja appletu
     */    
    public void init() 
    { 	
		fotoNames = new ArrayList<String>();	
	
		try 
		{			
			DefaultHandler handler = new SaxParser();
			SAXParserFactory spfactory = SAXParserFactory.newInstance();
			spfactory.setValidating(true);
			URL xml = new URL(getCodeBase(),"Fotos.xml");
			SAXParser parser = spfactory.newSAXParser();
			
			parser.parse(xml.openStream(), handler);
			fotos = new Image[numberOfFotos];
		}
		catch(Exception e) 
		{
			e.printStackTrace();
			String message = "Nie można wczytać pliku Fotos.xml";
	   		JOptionPane.showMessageDialog(this, message);
		}  
				
        scaleInit();   
    			
    	//Zakładka: "Galeria"
    	JPanel zdj = new JPanel();
    	zdj.setLayout(new BorderLayout());                       	
    	    	 
    	header = new JLabel("", JLabel.CENTER);
    	header.setFont(new Font("Verdena", Font.BOLD, 14));
    	header.setBackground(backgroundColor); 
    	header.setOpaque(true); 
    	
    	pasekTop = new JLabel(" ", JLabel.CENTER);
    	pasekTop.setFont(new Font("Helvetica", Font.PLAIN, 4));
    	pasekTop.setBackground(buttonBarBackgroundColor); 
    	pasekTop.setOpaque(true);
    	
    	pasekBottom = new JLabel(" ", JLabel.CENTER);
    	pasekBottom.setFont(new Font("Helvetica", Font.PLAIN, 4));
    	pasekBottom.setBackground(buttonBarBackgroundColor); 
    	pasekBottom.setOpaque(true);    		
	
    	tlo = new JLabel("",JLabel.CENTER);
    	tlo.setBackground(panelBarBackgroundColor); 
    	tlo.setOpaque(true);
    	tlo.addMouseMotionListener(this);
    	scrollPane = new JScrollPane(tlo);
       	scrollPane.setOpaque(true);
    	
    	// Przyciski przewijania zdjęć
    	ImageIcon auto = new ImageIcon (getClass().getResource("images/media/auto.png"));  
       	buttonAuto = new JToggleButton(auto);
       	buttonAuto.setToolTipText("Autopokaz");
      	
      	ImageIcon next = new ImageIcon (getClass().getResource("images/media/next.png"));
      	buttonNext = new JButton(next); 
      	buttonNext.setToolTipText("Następne");
      	
      	ImageIcon back = new ImageIcon (getClass().getResource("images/media/previous.png"));
      	buttonBack = new JButton(back);
      	buttonBack.setToolTipText("Poprzednie");
      	
      	ImageIcon pierwszy = new ImageIcon (getClass().getResource("images/media/first.png"));
      	buttonFirst = new JButton(pierwszy);
      	buttonFirst.setToolTipText("Pierwsze");
      	
      	ImageIcon ostatni = new ImageIcon (getClass().getResource("images/media/last.png"));
      	buttonEnd = new JButton(ostatni);
      	buttonEnd.setToolTipText("Ostatnie");
      	
      	ImageIcon zoom_in = new ImageIcon (getClass().getResource("images/media/zoom_in.png"));
      	buttonZoomIn = new JButton(zoom_in);
      	buttonZoomIn.setToolTipText("Powiększ");
      	
      	ImageIcon zoom_out = new ImageIcon (getClass().getResource("images/media/zoom_out.png"));
      	buttonZoomOut = new JButton(zoom_out);
      	buttonZoomOut.setToolTipText("Pomniejsz");
      	      	
      	ImageIcon zoom_original = new ImageIcon (getClass().getResource("images/media/zoom_original.png"));
      	buttonZoomOriginal = new JButton(zoom_original);
      	buttonZoomOriginal.setToolTipText("Rozmiar oryginalny");
      	      	      	  	
      	JPanel buttonBar = new JPanel(new FlowLayout(FlowLayout.CENTER,6,1));      
      	buttonBar.setBackground(buttonBarBackgroundColor); 
    	buttonBar.setOpaque(true); 		
    		    	    	    	
    	buttonBar.add(buttonFirst);
      	buttonBar.add(buttonBack);
      	buttonBar.add(buttonAuto);
      	buttonBar.add(buttonNext);
      	buttonBar.add(buttonEnd);      	
      	buttonBar.add(Box.createHorizontalStrut(10));		
      	buttonBar.add(buttonZoomOut);
      	buttonBar.add(buttonZoomIn);
      	buttonBar.add(buttonZoomOriginal);
      	
      	buttonAuto.addActionListener(this); 
      	buttonNext.addActionListener(this);
      	buttonBack.addActionListener(this);
      	buttonFirst.addActionListener(this);
      	buttonEnd.addActionListener(this);
      	buttonZoomIn.addActionListener(this);
      	buttonZoomOut.addActionListener(this);
      	buttonZoomOriginal.addActionListener(this);
      	      	   	     	
      	// Panele główne
      	JPanel panel = new JPanel(new BorderLayout());
    	panel.add(header,BorderLayout.NORTH);
    	panel.add(scrollPane,BorderLayout.CENTER);

    	JPanel panelBottom = new JPanel(new BorderLayout());
    	panelBottom.add(pasekTop, BorderLayout.NORTH);
    	panelBottom.add(buttonBar, BorderLayout.CENTER);
    	panelBottom.add(pasekBottom, BorderLayout.SOUTH);
    	
      	zdj.add(panel,BorderLayout.CENTER);
       	zdj.add(panelBottom,BorderLayout.SOUTH);            	      	 	
      	
   		// Zakładka: "O autorze"   	
      	JPanel author = new JPanel();
    	author.setLayout(new BorderLayout());                       	
    	
    	JPanel authorPanel = new JPanel(new BorderLayout()); 
      	authorPanel.setBackground(panelBarBackgroundColor); 
    	authorPanel.setOpaque(true);
    	
    	JPanel fillSpacerSouth = new JPanel();
    	fillSpacerSouth.setBackground(buttonBarBackgroundColor);
    	fillSpacerSouth.add(new JLabel("<html><br /><br /><br /><br /><br /></html>"));
    	fillSpacerSouth.setOpaque(true);
    	
    	JPanel fillSpacerNorth = new JPanel();
    	fillSpacerNorth.setBackground(buttonBarBackgroundColor);
    	fillSpacerNorth.add(new JLabel("<html><br /><br /><br /><br /><br /></html>"));
    	fillSpacerNorth.setOpaque(true);
    	
    	JPanel fillSpacerWest = new JPanel();
    	fillSpacerWest.setBackground(buttonBarBackgroundColor);
    	fillSpacerWest.add(new JLabel("<html><table width=100><tr><td> </td></tr></table></html>"));
    	fillSpacerWest.setOpaque(true);
    	
    	JPanel fillSpacerEast = new JPanel();
    	fillSpacerEast.setBackground(buttonBarBackgroundColor);
    	fillSpacerEast.add(new JLabel("<html><table width=100><tr><td> </td></tr></table></html>"));
    	fillSpacerEast.setOpaque(true);    	
    	    	
    	JLabel authorLabel = new JLabel("<html><table border=6><tr><td><div style='width: 314px; height:244px; text-align: center; margin: 2px 2px 2px 2px; font-size: 14pt; font-weight: lighter; font-family: Verdana, Arial, Helvetica, sans-serif;'><b><p align='center'><h2>Projekt z przedmiotu:</h2></p>&#8220;Programowanie w języku JAVA&#8221;</b> <br /><br /><br /><br /><em /><b />Przeglądarka zdjęć</b></em><br><br />Autor: Magdalena Fień</a><br /> <br /><br /><br />Rzeszów 2007</div></td></tr></table></html>",JLabel.CENTER);
       	authorPanel.add(authorLabel,BorderLayout.CENTER);       	  
    	author.add(authorPanel,BorderLayout.CENTER);   
    	author.add(fillSpacerEast,BorderLayout.EAST);   
    	author.add(fillSpacerWest,BorderLayout.WEST);   
    	author.add(fillSpacerNorth,BorderLayout.NORTH);   
    	author.add(fillSpacerSouth,BorderLayout.SOUTH);   
    	
      	// Tworzenie zakładek i dodanie komponentów do zakładek
        JTabbedPane zakladki = new JTabbedPane();        
       	zakladki.addTab("Galeria",null, zdj, "Zdjęcia");
        zakladki.addTab("Autor",null, author, "O autorze");    
        add(zakladki);        
        
        // Inicjowanie pierwszego zdjęcia 
        showNext();      	      	    	
    }
    
    /**
     *Funkcja odświeżająca aktualnie wyśwetlane zdjęcie
     */    
    public void refresh() 
    {
    	try 
    	{        	
           	fotos[i] = getImage(getDocumentBase(),"images/" + fotoNames.get(i));           	
           	fotos[i] = fotos[i].getScaledInstance(width, height, Image.SCALE_DEFAULT);           	
           	tlo.setIcon(new ImageIcon (fotos[i]));
           	//tlo.setLocation(x,y);
           	Graphics graph = fotos[i].getGraphics();
           	
           	if(width > widthConst)
           		tlo.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
           	else
           	    tlo.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
           	           	       	
        	header.setText("Zdjęcie: " + (i + 1) + " / " + fotos.length);
          	header.setForeground(new Color(255,255,255));        	
    	}
    	catch(Exception e) 
    	{
    		e.printStackTrace();
    	}
    }
    
    /**
     *Funkcja obsługująca pokaz następnego zdjęcia 
     */    
    public void showNext() 
    {
        i = i + 1;
        if (i >= fotos.length) i= 0; 
        refresh();
    }
    
    /**
     *Funkcja obsługująca pokaz poprzedniego zdjęcia 
     */
    public void showPrev() 
    {
        i = i - 1;
        if (i < 0)
            i = fotos.length-1; 
        refresh();
    }
    
    Timer t = new Timer(2000, new ActionListener() 
    {
         public void actionPerformed(ActionEvent e) 
         { 
         	showNext();
         }
    });	    
    
    /**
     *Funkcja obsługująca ActionListener'y
     */    	 
    public void actionPerformed(ActionEvent e) 
    {   
        if (e.getSource() == buttonNext)
        {
        	scaleInit();                 
            showNext(); 
        }
              
        else if (e.getSource() == buttonBack)
        {
        	scaleInit();
        	showPrev();        	
        }  
        
 	  	else if (e.getSource() == buttonAuto) 
 	  	{
 	  		scaleInit();
 	  		
            if (buttonAuto.isSelected()) 
            {
               t.start();
               buttonNext.setEnabled(false);
               buttonBack.setEnabled(false);
               buttonFirst.setEnabled(false);
               buttonEnd.setEnabled(false);
               buttonZoomIn.setEnabled(false);
               buttonZoomOut.setEnabled(false);
            }
            else 
            {
               t.stop();
               buttonNext.setEnabled(true);
               buttonBack.setEnabled(true);
               buttonFirst.setEnabled(true);
               buttonEnd.setEnabled(true);
               buttonZoomIn.setEnabled(true);
               buttonZoomOut.setEnabled(true);
            }
        }  
        
        else if (e.getSource() == buttonFirst) 
        {
        	i=0; 
        	scaleInit();
        	refresh();
        }
        
        else if (e.getSource() == buttonEnd) 
        {
        	i=fotos.length-1; 
        	scaleInit();
        	refresh();
        }
        
        else if (e.getSource() == buttonZoomIn) 
        {
        	width *= 1.2; 
			height *= 1.2;
			refresh();
        }
        
        else if (e.getSource() == buttonZoomOut) 
        {
        	width *= 0.8; 
			height *= 0.8;
			refresh();
        }
        
        else if (e.getSource() == buttonZoomOriginal) 
        {
        	scaleInit();
        	refresh();
        }
       
   }
   
   public void mouseMoved(MouseEvent e) 
   {
   	;   	
   }

    public void mouseDragged(MouseEvent e) 
    {
    	x = e.getX();
    	y = e.getY();
    	       
        System.out.println("Nacisnieto" 
                        + " (" + x + "," + y + ")"
                        + " wykryto w "
                        + e.getComponent().getClass().getName()
                        + "\n");
       
    }
    	
	/**
	 *Klasa uchwytu dla parsera
	 */
	class SaxParser extends DefaultHandler 
	{	
		boolean name = false;
		String attribut = "foto"; 
		String atrybut = "";
	
		/**
		 *Metoda parsowania 
		 */
		public void startElement(String nsURI, String sNazwa, String NazwaElementu, Attributes ats) 
		{
			if (NazwaElementu.equals("file")) 
			{
				name = true; 
				numberOfFotos++;
			}
			
			if (NazwaElementu.equals("item"))
				atrybut = ats.getValue(0);			
		}

		/**
		 *Metoda parsowania 
		 */
		public void characters(char bufor[], int offset, int lenght) 
		{
			String s = new String(bufor, offset, lenght);
			if (name) 	
			{
				name = false;
				
				if (atrybut.equals("foto")) 
					fotoNames.add(s);								
			}	
		}
	}	
}

Zdjęcia wczytywane są z pliku Fotos.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
	<item typ="foto">
		<file>animal1.jpg</file>
	</item>
	<item typ="foto">
		<file>animal2.jpg</file>
	</item>
	<item typ="foto">
		<file>animal3.jpg</file>
	</item>
	<item typ="foto">
		<file>animal4.jpg</file>
	</item>
	<item typ="foto">
		<file>animal5.jpg</file>
	</item>
	<item typ="foto">
		<file>animal6.jpg</file>
	</item>	
	<item typ="foto">
		<file>auto1.jpg</file>
	</item>
	<item typ="foto">
		<file>auto2.jpg</file>
	</item>
	<item typ="foto">
		<file>auto3.jpg</file>
	</item>
	<item typ="foto">
		<file>auto4.jpg</file>
	</item>
	<item typ="foto">
		<file>auto5.jpg</file>
	</item>
	<item typ="foto">
		<file>auto6.jpg</file>
	</item>
	<item typ="foto">
		<file>pic1.jpg</file>
	</item>
	<item typ="foto">
		<file>pic2.jpg</file>
	</item>
	<item typ="foto">
		<file>pic3.jpg</file>
	</item>
	<item typ="foto">
		<file>pic4.jpg</file>
	</item>
	<item typ="foto">
		<file>pic5.jpg</file>
	</item>
	<item typ="foto">
		<file>pic6.jpg</file>
	</item>	
</data>

Bardzo proszę o Was pomoc i z góry dzięki za wszelkie sugestie.
Pozdrawiam

0
  1. Skompiluj w javie 1.5 bo na 1.6 to mało jeszcze osób pracuje :)
  2. google -> Java Drag and Drop weź dowolny przykład i przerób do swoich potrzeb :)
0

Próbowałem stosować technikę drag, ale nie bardzo wiem jak zmieniać współrzędne obrazka (problem śledzenia współrzędnych myszy przy naciśnietym przycisku to żaden kłopot) :-/ Całe rysowanie odbywa sie w funkcji refresh(), a z tego co wiem to ustalenie pozycji obiektu graficznego możliwe jest z wykorzystaniem Graphics albo Graphics2D. Ja tutaj tego nie stosuje, dlatego pytam czy ktoś ma pomysł na rozwiązanie tego problemu w tym projekcie.
Nadal czekam na sugestię i pozdrawiam

1 użytkowników online, w tym zalogowanych: 0, gości: 1