Swing Rechteck und Kreise verschieben

  • Themenstarter Themenstarter Eny
  • Beginndatum Beginndatum
E

Eny

Gast
Hi Leute,

ich sitze hier schon länger an diesem Code und schaffe es einfach nicht meine erzeugten Rechecke und Kreise zu verschieben.
Ich habe es auch schon soweit geschafft das "er" erkennt welches Object ich grade anklicke. Nun muss ich diesen nur noch verschieben können. Die Rechecke oder Kreise sollen sich nicht permanent repainten, reicht auch, wenn sie einfach an einer anderen Stelle wieder gezeichnet werden.

Hier mal mein Code:

Java:
package aufgaben_GRAFIK;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Point2D;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;

public class RectDrawer extends JFrame implements ActionListener {
	// Neues Objekt von FigurZustand erstellen + ButtonGroup + GraphicPanel
	FigurZustand zu = new FigurZustand(getX(), getY(), 0, 0);
	private ButtonGroup group = new ButtonGroup();
	GraphicPanel gp = new GraphicPanel();

	// Vector erstellen
	private Vector rectList;

	// Eine globale Variable vom "Typ" FigurZustand, für das aktuelle Rechteck
	// deklarieren
	private FigurZustand currentRect;

	// Eine globale Variable für die Farbe deklarieren mit dem Startwert Grün
	private Color color = Color.green;

	// Eine globale Variable von ToolBar deklarieren
	private JToolBar toolBar;

	// Globale Variablen für die verschiedenen Zustände deklarieren
	private boolean isRectPressed = true;
	private boolean isKreisPressed = true;
	private boolean isStandardPressed;

	// Neue JRaidiobuttons global deklarieren und erstellen
	private JRadioButton rechteckButton = new JRadioButton("Erzeuge Rechteck");
	private JRadioButton kreisButton = new JRadioButton("Erzeuge Kreis");
	private JRadioButton standardButton = new JRadioButton("Standard");

	// Variablen erstellen die das aktuell ausgewählte Element speichert
	private FigurZustand selectedRect;

	// Main-Methode
	public static void main(String[] args) {
		RectDrawer wnd = new RectDrawer();
	}

	// Konstruktor der Klasse RectDrawer
	public RectDrawer() {
		super("Rechtecke zeichnen");

		// Buttons der ButtonGroup zuordnen
		group.add(rechteckButton);
		group.add(kreisButton);
		group.add(standardButton);

		// ActionListener an die Buttons anheften
		rechteckButton.addActionListener(this);
		kreisButton.addActionListener(this);
		standardButton.addActionListener(this);

		// Neuer Vector erstellen und ein Objekt von FigurZustände
		rectList = new Vector();
		currentRect = new FigurZustand(0, 0, 0, 0);

		// Layout auf BorderLayout setzen
		setLayout(new BorderLayout());

		// Neues Objekt von der ToolBar erstellen + Position bestimmen + Buttons
		// anbringen
		toolBar = new JToolBar();
		toolBar.setFloatable(true);
		add(toolBar, BorderLayout.PAGE_START);
		toolBar.add(rechteckButton);
		toolBar.add(kreisButton);
		toolBar.add(standardButton);

		// Mein GraphicPanel
		add("Center", gp);

		addWindowListener(new MyWindowListener());
		gp.addMouseListener(new MyMouseListener());
		gp.addMouseMotionListener(new MyMouseMotionListener());

		// JPanel bp = new JPanel();
		// bp.setBackground(Color.gray);
		// add("North", bp);

		setLocation(200, 200);
		setSize(400, 300);
		setVisible(true);

	}

	public void actionPerformed(ActionEvent e) {
		String label = ((JRadioButton) e.getSource()).getText();

		if (e.getSource() == kreisButton) {
			isKreisPressed = true;
			isRectPressed = false;
			isStandardPressed = false;
			repaint();
			System.out.println("Kreis");
		}

		if (e.getSource() == rechteckButton) {
			isKreisPressed = false;
			isRectPressed = true;
			isStandardPressed = false;
			repaint();
			System.out.println("Rechteck");
		}

		if (e.getSource() == standardButton) {
			isKreisPressed = false;
			isRectPressed = false;
			isStandardPressed = true;
			repaint();
		}
		// Graphics g = getGraphics();
		// drawRects(g);

	}

	public void drawRects(Graphics g) {

		FigurZustand r;
		Enumeration e;

		g.clearRect(0, 0, getSize().width, getSize().height);
		g.setColor(color);

		if (currentRect != null) {
			if (currentRect.isRect()) {
				g.drawRect(currentRect.x, currentRect.y, currentRect.width,
						currentRect.height);
			}
			if (currentRect.isOval()) {
				g.drawOval(currentRect.x, currentRect.y, currentRect.width,
						currentRect.height);
			}
		}

		for (e = rectList.elements(); e.hasMoreElements();) {
			r = (FigurZustand) e.nextElement();

			if (r != null) {

				if (r.isRect()) {
					g.drawRect(r.x, r.y, r.width, r.height);
				}
				if (r.isOval()) {
					g.drawOval(r.x, r.y, r.width, r.height);
				}
			}
		}
	}

	class MyMouseListener extends MouseAdapter {
		public void mousePressed(MouseEvent event) {
			if (isKreisPressed || isRectPressed) {
				currentRect = new FigurZustand(event.getX(), event.getY(), 0, 0);
				if (isRectPressed) {
					currentRect.setRect(true);
					currentRect.setOval(false);
				}
				if (isKreisPressed) {
					currentRect.setRect(false);
					currentRect.setOval(true);
				}
			} else if (isStandardPressed) {
				System.out.println("mousePressed isStandardPressed");

				for (Enumeration e = rectList.elements(); e.hasMoreElements();) {
					FigurZustand r = (FigurZustand) e.nextElement();
					selectedRect = r;

					if (event.getPoint().getX() >= selectedRect.getX()
							&& event.getPoint().getX() <= selectedRect.getX()
									+ selectedRect.width
							&& event.getPoint().getY() >= selectedRect.getY()
							&& event.getPoint().getY() <= selectedRect.getY()
									+ selectedRect.width) {
						
					}
					
						System.out.println("SelectedRect found");
				}
			}

		}

		public void mouseReleased(MouseEvent event) {
			if (isKreisPressed || isRectPressed) {
				if (currentRect.width > 0 || currentRect.height > 0) {
					rectList.addElement(currentRect);
					currentRect = null;
				}

				// Graphics g = getGraphics();
				// drawRects(g);
				repaint();
			} else if (isStandardPressed) {
				System.out.println("mouseReleased isStandardPressed");
				System.out.println("----------------------------");
			}
		}
	}

	class MyMouseMotionListener extends MouseMotionAdapter {
		public void mouseDragged(MouseEvent event) {
			if (isKreisPressed || isRectPressed) {
				int x = event.getX();
				int y = event.getY();
				if (x > currentRect.x && y > currentRect.y) {
					currentRect.width = x - currentRect.x;
					currentRect.height = y - currentRect.y;
				}

				// Graphics g = getGraphics();
				// drawRects(g);
				repaint();
			} else if (isStandardPressed) {
				System.out.println("mouseDragged isStandardPressed");
			}
		}
	}

	class MyWindowListener extends WindowAdapter {
		public void windowClosing(WindowEvent event) {
			setVisible(false);
			dispose();
			System.exit(0);
		}
	}

	class GraphicPanel extends JPanel {
		public void paint(Graphics g) {
			super.paint(g);
			drawRects(g);
		}
	}
}

Weiß, ist nicht der schönste Progstil aber muss zur meiner Verteidigung sagen, dass ich dieses Prog von AWT in SWING umgewandelt habe und ebenfalls schon vorgegeben war (zum Teil halt)

Vielen Dank schonmal für die Mühe

LG, Eny
 
nettes Programm, hab dir eine Lösung eingebaut,
siehe die drei Listener:
Java:
public class Test {
    public static void main(String[] args)  {
        RectDrawer wnd = new RectDrawer();
    }
}

class RectDrawer
    extends JFrame
    implements ActionListener
{
    // Neues Objekt von FigurZustand erstellen + ButtonGroup + GraphicPanel
    FigurZustand zu = new FigurZustand(getX(), getY(), 0, 0);
    private ButtonGroup group = new ButtonGroup();
    GraphicPanel gp = new GraphicPanel();

    // Vector erstellen
    private Vector rectList;

    // Eine globale Variable vom "Typ" FigurZustand, für das aktuelle Rechteck
    // deklarieren
    private FigurZustand currentRect;

    // Eine globale Variable für die Farbe deklarieren mit dem Startwert Grün
    private Color color = Color.green;

    // Eine globale Variable von ToolBar deklarieren
    private JToolBar toolBar;

    // Globale Variablen für die verschiedenen Zustände deklarieren
    private boolean isRectPressed = true;
    private boolean isKreisPressed = true;
    private boolean isStandardPressed;

    // Neue JRaidiobuttons global deklarieren und erstellen
    private JRadioButton rechteckButton = new JRadioButton("Erzeuge Rechteck");
    private JRadioButton kreisButton = new JRadioButton("Erzeuge Kreis");
    private JRadioButton standardButton = new JRadioButton("Standard");

    // Variablen erstellen die das aktuell ausgewählte Element speichert
    private FigurZustand selectedRect;
    private Point beginMovement;

    // Konstruktor der Klasse RectDrawer
    public RectDrawer()
    {
        super("Rechtecke zeichnen");

        // Buttons der ButtonGroup zuordnen
        group.add(rechteckButton);
        group.add(kreisButton);
        group.add(standardButton);

        // ActionListener an die Buttons anheften
        rechteckButton.addActionListener(this);
        kreisButton.addActionListener(this);
        standardButton.addActionListener(this);

        // Neuer Vector erstellen und ein Objekt von FigurZustände
        rectList = new Vector();
        currentRect = new FigurZustand(0, 0, 0, 0);

        // Layout auf BorderLayout setzen
        setLayout(new BorderLayout());

        // Neues Objekt von der ToolBar erstellen + Position bestimmen + Buttons
        // anbringen
        toolBar = new JToolBar();
        toolBar.setFloatable(true);
        add(toolBar, BorderLayout.PAGE_START);
        toolBar.add(rechteckButton);
        toolBar.add(kreisButton);
        toolBar.add(standardButton);

        // Mein GraphicPanel
        add("Center", gp);

        addWindowListener(new MyWindowListener());
        gp.addMouseListener(new MyMouseListener());
        gp.addMouseMotionListener(new MyMouseMotionListener());

        // JPanel bp = new JPanel();
        // bp.setBackground(Color.gray);
        // add("North", bp);

        setLocation(200, 200);
        setSize(400, 300);
        setVisible(true);

    }

    public void actionPerformed(ActionEvent e)
    {
        String label = ((JRadioButton)e.getSource()).getText();

        if (e.getSource() == kreisButton)
        {
            isKreisPressed = true;
            isRectPressed = false;
            isStandardPressed = false;
            repaint();
            System.out.println("Kreis");
        }

        if (e.getSource() == rechteckButton)
        {
            isKreisPressed = false;
            isRectPressed = true;
            isStandardPressed = false;
            repaint();
            System.out.println("Rechteck");
        }

        if (e.getSource() == standardButton)
        {
            isKreisPressed = false;
            isRectPressed = false;
            isStandardPressed = true;
            repaint();
        }
        // Graphics g = getGraphics();
        // drawRects(g);

    }

    public void drawRects(Graphics g)
    {

        FigurZustand r;
        Enumeration e;

        g.clearRect(0, 0, getSize().width, getSize().height);
        g.setColor(color);

        if (currentRect != null)
        {
            if (currentRect.isRect())
            {
                g.drawRect(currentRect.x, currentRect.y, currentRect.width, currentRect.height);
            }
            if (currentRect.isOval())
            {
                g.drawOval(currentRect.x, currentRect.y, currentRect.width, currentRect.height);
            }
        }

        for (e = rectList.elements(); e.hasMoreElements();)
        {
            r = (FigurZustand)e.nextElement();

            if (r != null)
            {

                if (r.isRect())
                {
                    g.drawRect(r.x, r.y, r.width, r.height);
                }
                if (r.isOval())
                {
                    g.drawOval(r.x, r.y, r.width, r.height);
                }
            }
        }
    }

    class MyMouseListener
        extends MouseAdapter
    {
        public void mousePressed(MouseEvent event)
        {
            Point p = event.getPoint();
            if (isKreisPressed || isRectPressed)
            {
                currentRect = new FigurZustand(p.x, p.y, 0, 0);
                if (isRectPressed)
                {
                    currentRect.setRect(true);
                    currentRect.setOval(false);
                }
                if (isKreisPressed)
                {
                    currentRect.setRect(false);
                    currentRect.setOval(true);
                }
            }
            else if (isStandardPressed)
            {
                System.out.println("mousePressed isStandardPressed");

                for (Enumeration e = rectList.elements(); e.hasMoreElements();)
                {
                    FigurZustand r = (FigurZustand)e.nextElement();
                    System.out.println("r: " + r.x + ", " + r.y);

                    System.out.println("p: " + p.x + ", " + p.y);
                    if (p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.width)
                    {
                        selectedRect = r;
                        beginMovement = new Point(p.x - r.x, p.y - r.y);
                        System.out.println("SelectedRect found");
                    }

                }
            }

        }

        public void mouseReleased(MouseEvent event)
        {
            if (isKreisPressed || isRectPressed)
            {
                if (currentRect.width > 0 || currentRect.height > 0)
                {
                    rectList.addElement(currentRect);
                    currentRect = null;
                }

                // Graphics g = getGraphics();
                // drawRects(g);
                repaint();
            }
            else if (isStandardPressed)
            {
                System.out.println("mouseReleased isStandardPressed");
                System.out.println("----------------------------");

                selectedRect = null;
                beginMovement = null;
            }
        }
    }

    class MyMouseMotionListener
        extends MouseMotionAdapter
    {
        public void mouseDragged(MouseEvent event)
        {
            Point p = event.getPoint();
            if (isKreisPressed || isRectPressed)
            {
                int x = p.x;
                int y = p.y;
                if (x > currentRect.x && y > currentRect.y)
                {
                    currentRect.width = x - currentRect.x;
                    currentRect.height = y - currentRect.y;
                }

                // Graphics g = getGraphics();
                // drawRects(g);
                repaint();
            }
            else if (isStandardPressed)
            {
                // System.out.println("mouseDragged isStandardPressed");
                if (selectedRect != null)
                {
                    selectedRect.x = p.x - beginMovement.x;
                    selectedRect.y = p.y - beginMovement.y;
                    repaint();
                }

            }
        }
    }

    class MyWindowListener
        extends WindowAdapter
    {
        public void windowClosing(WindowEvent event)
        {
            setVisible(false);
            dispose();
            System.exit(0);
        }
    }

    class GraphicPanel
        extends JPanel
    {
        public void paint(Graphics g)
        {
            super.paint(g);
            drawRects(g);
        }
    }
}


class FigurZustand
{
    int x;
    int y;
    int width;
    int height;
    boolean rect;
    boolean oval;

    public FigurZustand(int x, int y, int width, int height)
    {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public int getWidth()
    {
        return this.width;
    }

    public void setWidth(int width)
    {
        this.width = width;
    }

    public int getHeight()
    {
        return this.height;
    }

    public void setHeight(int height)
    {
        this.height = height;
    }

    public boolean isRect()
    {
        return this.rect;
    }

    public void setRect(boolean rect)
    {
        this.rect = rect;
    }

    public boolean isOval()
    {
        return this.oval;
    }

    public void setOval(boolean oval)
    {
        this.oval = oval;
    }

}
 
Ja fetten Dank.

Ich glaub darauf wäre ich nie gekommen....sorry das ich dir die Klasse Figurzustand nicht mit gegeben hab....hast auch schnell so nebenbei mal geschrieben 😀:toll:
 
Hallo Eny,

hier noch einige allgemeine Hinweise:
- Die Klasse Vector ist veraltet. Statt dessen werden die neuen Collection Klassen empfohlen, wie z.B. ArrayList.

- In Swing wird empfohlen, dass wir zum Zeichnen auf eine Komponente nicht paint überschreiben, sondern paintComponent. Siehe auch: Malen in Swing Teil 1: der grundlegende Mechanismus - Byte-Welt Wiki

- Auch gibt man gewöhnlich an, was in die Liste kommen soll:
Java:
private List<FigurZustand> rectList;
...
rectList = new ArrayList<FigurZustand>();
Dann ist es auch einfacher, die Liste zu durchlaufen:
Java:
for (FigurZustand r : rectList) {
...
}

Gruß,
André
 
Zuletzt bearbeitet:

Zurück
Oben