MouseDragging

Status
Nicht offen für weitere Antworten.
A

AndreasS

Gast
Hallo,

habe ein (für mich) schwieriges Problem, da ich Anfänger bin. Ich soll für morgen folgende :cry: Praktikumsaufgabe programmieren:

"Auf ein Mouse-Dragging soll folgendermaßen reagiert werden:
Befindet sich die Maus links vom Label (bzw. Button) und ist der horizontale Abstand von der Maus zum Label (bzw. Button) kleiner als 5 Pixel, so wird das Label (bzw. der Button) um 5 Pixel nach rechts verschoben.
Befindet sich die Maus rechts vom Label (bzw. Button) und ist der horizontale Abstand von der Maus zum Label (bzw. Button) kleiner als 5 Pixel, so wird das Label (bzw. der Button) um 5 Pixel nach links verschoben.
Befindet sich die Maus oberhalb des Labels (bzw. Buttons) und ist der vertikale Abstand von der Maus zum Label (bzw. Button) kleiner als 5 Pixel, so wird das Label (bzw. der Button) um 5 Pixel nach unten verschoben.
Befindet sich die Maus unterhalb des Labels (bzw. Buttons) und ist der vertikale Abstand von der Maus zum Label (bzw. Button) kleiner als 5 Pixel, so wird das Label (bzw. der Button) um 5 Pixel nach oben verschoben."

Ist wahrscheinlich nicht wirklich schwer, habe aber keinen blassen Schimmer.
Für jeden Hinweis oder Anregung bin ich dankbar!

Gruß Andreas
 
B

Beni

Gast
Also "kein blasser Schimmer" ist eine etwas unklare Angabe. Weisst du wenigstens wie man ein Java-Prog startet?

Na egal, ich mach einen kleinen Beispielcode:
Code:
// Viele verschiedene Imports, diese Klassen werden wir benötigen
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;

// Die Hauptklasse
public class Main{
    
    // Die Startmethode
    public static void main(String[] args){
        JFrame frame = new JFrame(); // Das Frame, welches das Label darstellen wird
        final Container content = frame.getContentPane(); // Das ContentPane auf dem das Label liegen wird
        content.setLayout( null ); // Das ContentPane darf kein Layout haben, da wir für die Position des Labels selber sorgen
        
        final JLabel label = new JLabel( "Schieb mich" ); // Das Label
        
        label.setOpaque( true ); // Das Label soll einen Hintergrund besitzen
        
        // Das Label farblich vom Rest abheben
        label.setBackground( Color.RED );
        content.setBackground( Color.WHITE );
        
        // Dem Label einen MouseMotionListener zuordnen.
        // Der Listener wird als anonyme Klasse implementiert
        label.addMouseMotionListener( new MouseMotionListener(){
            public void mouseDragged(MouseEvent e) {
                // Position der Maus relativ zum Label
                int x = e.getX();
                int y = e.getY();
                
                // Position des Labels
                int locationx = label.getX();
                int locationy = label.getY();
                
                // Grösse des Labels
                Dimension size = label.getSize();
                
                // Verschieben in x-Richtung
                if( x < 0 && x >= -5 )
                    locationx += 5;
                else if( x > size.width && x <= size.width + 5 )
                    locationx -= 5;
                
                // Verschieben in y-Richtung
                if( y < 0 && y >= -5 )
                    locationy += 5;
                else if( y > size.height && y <= size.height + 5 )
                    locationy -= 6;
                
                // Dafür sorgen, dass das Label nicht zu weit verschoben wird
                locationx = Math.max( 0, locationx );
                locationx = Math.min( locationx, content.getWidth() - size.width );
                
                locationy = Math.max( 0, locationy );
                locationy = Math.min( locationy, content.getHeight() - size.height );
                
                // Änderungen speichern
                label.setLocation( locationx, locationy );
            }
            
            public void mouseMoved(MouseEvent e) {
                // do nothing
            }
        });
        
        // Label dem ContentPane hinzufügen
        content.add( label );
        // Startposition des Labels
        label.setBounds( 50, 50, 100, 30 );
        // Startposition des Frames
        frame.setBounds( 20, 20, 500, 500 );
        // Programm beenden, wenn Frame geschlossen wird
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        // Frame sichtbar machen
        frame.setVisible( true );
    }
}

Wichtig ist, dass du dem Label einen MouseMotionListener zuordnest. Dieser Listener wird benachrichtig, sobald die Maus gedrückt verschoben wurde.
Auch wichtig ist, dass der Container, auf dem das Label liegt, ein null-Layout besitzt. Da es sonst automatisch die Position des Labels verändern würde.

Eine genaue Definition der einzelnen Klassen und Methoden die ich hier verwendet habe, findest du in der API

mfg Beni
 
A

AndreasS

Gast
Hi,
danke für deine Hilfe. Habe aber noch ein Problem, den Code zu integrieren.
Hier mein Code:

Code:
//file: MouseDrag.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseDrag2 {
   // main panel container as parent for the labels
   JPanel   mainP;
   // Label and Button
   JLabel   xLab;
   JButton  xBut;
   

   // Mouse coordinates
   int   mouseX = 0;
   int   mouseY = 0;
 
   // Constructor
   public MouseDrag2() {
   	
      // Create a container 
      mainP = new JPanel();
      
      //Layout ausschalten
      mainP.setLayout(null); 
      
      // Create the label and button 
      xLab = new JLabel("Label für AS");
      //xLab.setSize(50,50);
      xLab.setBounds(50, 50, 100, 30); // (x,y, breite, höhe) 
      xBut = new JButton("Button für AS");
      xBut.setBounds(150, 150, 150, 50);// (x,y, breite, höhe) 
      //xBut.setSize(50,50);
      //xBut.setPreferredSize(newDimension(50,25));
    
      // Add the label/button to the container
      mainP.add(xLab);
      mainP.add(xBut);
      
      //mouse motion event handling/ action event handling by
      //adding mouse motion listener/actioon listener
      xBut.addActionListener(new MyActionListener());
      mainP.addMouseMotionListener(new MyMouseMotionListener());
      
      //xLab.addMouseMotionListener(new MyMouseMotionListener());
   }
   private class MyActionListener implements ActionListener {
   	public void actionPerformed( ActionEvent e )
  	{
  	// Exit -> Code für Label visible true/false -> xLab.setVisible(false)
    //System.exit( 0 ); für schließen
    	if(xLab.isVisible() != true){
    		xLab.setVisible(true);
    	}
    	else if(xLab.isVisible() != false){
    		xLab.setVisible(false);
    	}
  	}
	}
	
   }

   private class MyMouseMotionListener implements MouseMotionListener {
      // Methods of the MouseMotionListener interface 
      	public void mouseDragged(MouseEvent e) {
 				int x = e.getX(); 
                int y = e.getY(); 
                
                // Position des Labels 
                int locationx = xLab.getX(); 
                int locationy = xLab.getY(); 
                
                // Grösse des Labels 
                Dimension size = xLab.getSize(); 
                
                // Verschieben in x-Richtung 
                if( x < 0 && x >= -5 ) 
                    locationx += 5; 
                else if( x > size.width && x <= size.width + 5 ) 
                    locationx -= 5; 
                
                // Verschieben in y-Richtung 
                if( y < 0 && y >= -5 ) 
                    locationy += 5; 
                else if( y > size.height && y <= size.height + 5 ) 
                    locationy -= 6; 
                
                // Dafür sorgen, dass das Label nicht zu weit verschoben wird 
                locationx = Math.max( 0, locationx ); 
                locationx = Math.min( locationx, content.getWidth() - size.width ); 
                
                locationy = Math.max( 0, locationy ); 
                locationy = Math.min( locationy, content.getHeight() - size.height ); 
                
                // Änderungen speichern 
                xLab.setLocation( locationx, locationy ); 
            } 
      }
      public void mouseMoved(MouseEvent e) {}
   }
   
   // Main method 
   public static void main(String[] args) {
      // Create a frame as main application window 
      // with the specified title
      JFrame mainF = new JFrame("PushOffAS von Andreas Schindler");
      
      // Make the application exit when the window is closed.
      mainF.addWindowListener(new WindowAdapter(  ) {
         public void windowClosing(WindowEvent we) { 
            System.exit(0); 
         }
      });
      // Set width and height of the main window
      mainF.setLocation(100, 100);
      mainF.setSize(300, 300);//pass the width and height
     
      // Create a MouseDrag object
      MouseDrag2 drag = new MouseDrag2();
      // Add the main panel to the frame's content pane
      mainF.getContentPane( ).add(drag.mainP);
      mainF.setVisible(true);
   }
   
}

Beim Compilieren bringt er dauernd Fehlermeldungen. Wäre sehr nett von dir wenn du mir nochmals helfen würdest.

Grüße Andi
 
B

Beni

Gast
Diese schliessende Klammer vor dem MyMouseListener ist zuviel. Content noch durch dein Panel ersetzen. Der Rest sollte richtig sein (und sonst gibt es halt Fehlermeldungen :wink: )

mfg Beni
 
A

AndiS

Gast
Hi,
irgendwie haut das nicht hin...
Kann man den Button nicht auch verschieben? Komme einfach nicht weiter...
Hier nochmals mein Code:

Code:
//file: MouseDrag.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseDrag2 {
   // main panel container as parent for the labels
   JPanel   mainP;
   // Label and Button
   JLabel   xLab;
   JButton  xBut;
   
   // Mouse coordinates
   int   mouseX = 0;
   int   mouseY = 0;
 
   // Constructor
   public MouseDrag2() {
   	
      // Create a container 
      mainP = new JPanel();
      
      //Layout ausschalten
      mainP.setLayout(null); 
      
      // Create the label and button 
      xLab = new JLabel("Label für AS");
      xLab.setBounds(50, 50, 100, 30); // (x,y, breite, höhe) 
      xBut = new JButton("Button für AS");
      xBut.setBounds(150, 150, 150, 50);// (x,y, breite, höhe) 
        
      // Add the label/button to the container
      mainP.add(xLab);
      mainP.add(xBut);
      
      //mouse motion event handling/ action event handling by
      //adding mouse motion listener/actioon listener
      xBut.addActionListener(new MyActionListener());
      mainP.addMouseMotionListener(new MyMouseMotionListener());
      
      xLab.addMouseMotionListener(new MyMouseMotionListener());
   }
   private class MyActionListener implements ActionListener {
	   	public void actionPerformed( ActionEvent e )
	  	{
	    	if(xLab.isVisible() != true){
	    		xLab.setVisible(true);
	    	}
	    	else if(xLab.isVisible() != false){
	    		xLab.setVisible(false);
	    	}
	  	}
	}
	
   private class MyMouseMotionListener implements MouseMotionListener {
      // Methods of the MouseMotionListener interface 
      	public void mouseDragged(MouseEvent e) {
      			// für Label
 				int x = e.getX(); 
                int y = e.getY();
                 
                // für Button
                int xb = e.getX();
                int yb = e.getY();
                
                // Position des Labels 
                int locationx = xLab.getX(); 
                int locationy = xLab.getY(); 
                
                // Position des Buttons
                int locationxb = xLab.getX(); 
                int locationyb = xLab.getY(); 
                
                // Grösse des Labels 
                Dimension size = xLab.getSize(); 
                
                // Grösse des Buttons
                Dimension sizeb = xBut.getSize(); 
                
                // Verschieben in x-Richtung (Label)
                if( x < 0 && x >= -5 ) 
                    locationx += 5; 
                else if( x > size.width && x <= size.width + 5 ) 
                    locationx -= 5; 
                
                // Verschieben in y-Richtung (Label)
                if( y < 0 && y >= -5 ) 
                    locationy += 5; 
                else if( y > sizeb.height && y <= sizeb.height + 5 ) 
                    locationy -= 6; 
                
                // Verschieben in x-Richtung (Button)
                if( xb < 0 && xb >= -5 ) 
                    locationxb += 5; 
                else if( xb > sizeb.width && xb <= sizeb.width + 5 ) 
                    locationxb -= 5; 
                
                // Verschieben in y-Richtung (Button)
                if( yb < 0 && yb >= -5 ) 
                    locationyb += 5; 
                else if( yb > sizeb.height && yb <= sizeb.height + 5 ) 
                    locationyb -= 6; 
                    
                /* Dafür sorgen, dass das Label nicht zu weit verschoben wird 
                locationx = Math.max( 0, locationx ); 
                locationx = Math.min( locationx, content.getWidth() - size.width ); 
                
                locationy = Math.max( 0, locationy ); 
                locationy = Math.min( locationy, content.getHeight() - size.height );*/ 
                
                // Änderungen speichern 
                xLab.setLocation( locationx, locationy ); 
                xLab.setLocation( locationxb, locationyb ); 
            } 
      
      public void mouseMoved(MouseEvent e) {}
   }
   
   // Main method 
   public static void main(String[] args) {
      // Create a frame as main application window 
      // with the specified title
      JFrame mainF = new JFrame("PushOffAS von Andreas Schindler");
      
      // Make the application exit when the window is closed.
      mainF.addWindowListener(new WindowAdapter(  ) {
         public void windowClosing(WindowEvent we) { 
            System.exit(0); 
         }
      });
      // Set width and height of the main window
      mainF.setLocation(100, 100);
      mainF.setSize(300, 300);//pass the width and height
     
      // Create a MouseDrag object
      MouseDrag2 drag = new MouseDrag2();
      
      // Add the main panel to the frame's content pane
      mainF.getContentPane( ).add(drag.mainP);
      mainF.setVisible(true);
   }
   
}

Leider funktioniert das mit dem Button nicht und das mit dem content blicke ich auch irgendwie nicht.
So läuft der Code zwar ohne Fehlermeldung vom Compiler, aber er macht nicht das was er soll.
Das Programm habe ich mir irgendwie zusammengebastelt. Daher weiß ich nicht wirklich was es tut!
Bitte helfe mir nochmals...

Viele Grüße

Andi
 
B

Beni

Gast
Sag mal, wielange hattest du Zeit für diese Aufgabe?

Den Button kann man auch bewegen (ist ja klar).
Du fügst deinen MouseMotionListener einfach beiden Components hinzu. Aber eine Kleinigkeit muss verändert werden (jetzt ist er ja noch auf das Label ausgerichtet):
Code:
private class MyMouseMotionListener implements MouseMotionListener {
  public void mouseDragged(MouseEvent e) {
    // move ist die Component, die sich verschieben soll
    Component move = (Component)e.getSource();
  }
In dem MouseEvent ist gespeichert, über welcher Component die Maus gedrückt wurde. Wenn sie beim Button gedrückt wurde, ist der Button die Source, wenn es das Label war, ist es das Label.

Und diese Zeile hier: mainP.addMouseMotionListener(new MyMouseMotionListener()); ist überflüssig.

Ein Tipp für später: Du musst den Code genauer betrachten. Du hast mindestens 3 Variablen verwechselt.

Ich poste noch eine Version, die etwas besser funktioniert (auf den Button klicken, Maus gedrückt halten und langsam herumfahren):
Code:
public class MouseDrag2 {

    // main panel container as parent for the labels
    JPanel mainP;

    // Label and Button
    JLabel xLab;

    JButton xBut;

    // Mouse coordinates
    int mouseX = 0;

    int mouseY = 0;

    // Constructor
    public MouseDrag2() {

        // Create a container
        mainP = new JPanel();

        //Layout ausschalten
        mainP.setLayout(null);

        // Create the label and button
        xLab = new JLabel("Label für AS");
        xLab.setBounds(50, 50, 100, 30); // (x,y, breite, höhe)
        xBut = new JButton("Button für AS");
        xBut.setBounds(150, 150, 150, 50);// (x,y, breite, höhe)

        // Add the label/button to the container
        mainP.add(xLab);
        mainP.add(xBut);

        //mouse motion event handling/ action event handling by
        //adding mouse motion listener/actioon listener
        xBut.addActionListener(new MyActionListener());
        
        MyMouseMotionListener listener = new MyMouseMotionListener();

        xLab.addMouseMotionListener( listener );
        xBut.addMouseMotionListener( listener );
    }

    private class MyActionListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (xLab.isVisible() != true) {
                xLab.setVisible(true);
            } else if (xLab.isVisible() != false) {
                xLab.setVisible(false);
            }
        }
    }

    private class MyMouseMotionListener implements MouseMotionListener {

        // Methods of the MouseMotionListener interface
        public void mouseDragged(MouseEvent e) {
            Component move = (Component)e.getSource();
            
            // für Label
            int x = e.getX();
            int y = e.getY();

            // für Button
            int xb = e.getX();
            int yb = e.getY();

            // Position der Component
            int locationx = move.getX();
            int locationy = move.getY();

            // Grösse des Labels
            Dimension size = move.getSize();

            // Verschieben in x-Richtung (Label)
            if (x < 0 && x >= -5)
                locationx += 5;
            else if (x > size.width && x <= size.width + 5)
                locationx -= 5;

            // Verschieben in y-Richtung (Label)
            if (y < 0 && y >= -5)
                locationy += 5;
            else if (y > size.height && y <= size.height + 5)
                locationy -= 6;

            
            //  Dafür sorgen, dass die Component nicht zu weit verschoben wird
           locationx = Math.max( 0, locationx ); 
           locationx = Math.min( locationx, mainP.getWidth() - size.width );
            
           locationy = Math.max( 0, locationy ); 
           locationy = Math.min( locationy, mainP.getHeight() - size.height );

            // Änderungen speichern
            move.setLocation(locationx, locationy);
        }

        public void mouseMoved(MouseEvent e) {
        }
    }

    // Main method
    public static void main(String[] args) {
        // Create a frame as main application window
        // with the specified title
        JFrame mainF = new JFrame("PushOffAS von Andreas Schindler");

        // Make the application exit when the window is closed.
        mainF.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });
        // Set width and height of the main window
        mainF.setLocation(100, 100);
        mainF.setSize(300, 300);//pass the width and height

        // Create a MouseDrag object
        MouseDrag2 drag = new MouseDrag2();

        // Add the main panel to the frame's content pane
        mainF.getContentPane().add(drag.mainP);
        mainF.setVisible(true);
    }
}
 
A

Andreas S

Gast
Hi,
danke für deine super Hilfe! Hatte übrigens ne Woche für die Aufgabe Zeit...
Aber wie es halt so ist, immer auf den letzten Drücker.
Vor 2 Wochen konnte ich ja auch gerade mal "Hallo Welt" ausgeben. Werde mich jetzt aber richtig reinhängen!
Dann sollte es besser klappen...
Also nochmals Danke und Gruß
Andreas :D
 
Status
Nicht offen für weitere Antworten.

Neue Themen


Oben