mein keyListener scheint Konflict haben mit mouseListener

Status
Nicht offen für weitere Antworten.

kai

Mitglied
Unten ist mein Programm,
Ich will in meinem Programm so etwas realisieren, nähmlich nachdem ich textButton gedruckt und mouse auf PaintPanel gepressed und ein Text, die per Tastertur eingegeben wird, angezeigt wird, und zwar, beim Eingeben gleichzeitig erscheinen.
Jetzt das Problem ist wenn ich zuerst mouse irgendwo gedruckt dann das keyListener macht keine Arbeit mehr. Aber warum, verstehe ich das nicht. Darf keyListener, mouseListener eigentlich nicht gleichtzeitig benutzt werden? Ich finde nicht, aber aus welcher Grund kommt mein Problem? Kann jemand hier mir helfen?

Code:
package zeichnen;

/**
 * Date: 2004-5-8
 * author: jellen
 *         kaihua wu
 * Purpose: This is a simple drawing program.
 */

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import java.awt.geom.*;

class ProgrammZustand {
  // programm zustand
  public static final int SELECT = 1;
  public static final int LINE = 2;
  public static final int RECTANGLE = 3;
  public static final int ELLIPSE = 4;
  public static final int CIRCLE = 5;
  public static final int TEXT = 6;
  public static final int MOVE_OR_ERASE = 7;

  // zus鋞chlicher symbol
  public static final int RASTER = 8;
  public static final int PFEIL = 9;
  public static final int KREISBOGEN = 10;
  public static String text;
  protected int startX;
  protected int startY;
  protected int endX;
  protected int endY;
  protected int zustand;
  protected boolean isFrozen;
  protected boolean isSelected;
  protected boolean isFill;
  protected Color color;
  protected static final Color DEFAULTCOLOR_AS_BLACK = Color.BLACK;

  public ProgrammZustand()
  {
    isFrozen = false;
    isSelected = false;
    isFill = false;
    color = DEFAULTCOLOR_AS_BLACK;
  }
  public ProgrammZustand(int sx, int sy, int ex, int ey)
  {
    isFrozen = false;
    isSelected = false;
    isFill = false;
    color = DEFAULTCOLOR_AS_BLACK;
    startX = sx;
    startY = sy;
    endX = ex;
    endY = ey;
  }
  public void setStart(int x, int y)
  {
    startX = x;
    startY = y;
  }
  public void setEnd(int x, int y)
  {
    endX = x;
    endY = y;
  }
  public Point2D getStart()
  {
    Point2D point = new Point2D.Double(startX, startY);
    return point;
  }
  public Point2D getEnd()
  {
    Point2D point = new Point2D.Double(endX, endY);
    return point;
  }
  public int maxX()
  {
    int max_X =  (startX >= endX? startX : endX);
      return max_X;
  }
  public int minX()
  {
    int min_X = (startX <= endX? startX : endX);
      return min_X;
  }
  public int maxY()
  {
    int max_Y = (startY >= endY? startY : endY);
      return max_Y;
  }
  public int minY()
  {
    int min_Y = (startY <= endY? startY : endY);
      return min_Y;
  }
  public boolean isContain(int x, int y)
  {
    if(x >= minX() && x <= maxX() &&
       y >= minY() && y <= maxY())
      return true;
    else
      return false;
  }
  public void writeData(PrintWriter out)throws IOException
  {
    int c = color.getRGB();
    int fill;

    if( isFill )
      fill = 1;
    else
      fill = 0;

    out.println(zustand + "|" + c + "|" + fill + "|" +
                startX + "|" + startY + "|" + endX + "|" + endY);
  }

  public void readData(BufferedReader in)throws IOException
  {
    String s = in.readLine();
    StringTokenizer t = new StringTokenizer(s, "|");

    zustand = Integer.parseInt(t.nextToken());
    color = new Color(Integer.parseInt(t.nextToken()));
    int fill = Integer.parseInt(t.nextToken());
    if(fill == 1)
      isFill = true;
    else
      isFill = false;
    startX = Integer.parseInt(t.nextToken());
    startY = Integer.parseInt(t.nextToken());
    endX = Integer.parseInt(t.nextToken());
    endY = Integer.parseInt(t.nextToken());
  }

/*  public static void main(String[] args) {
//    Line line = new Line(1, 2, 3, 4);

//    System.out.print("The first: ");
//    System.out.println(line.getStart() + ", " + line.getEnd());

    try
    {
      PrintWriter out = new PrintWriter(new FileWriter("jellen.txt"));
//      line.writeData(out);
      out.close();

      BufferedReader in = new BufferedReader(new FileReader("jellen.txt"));
      Polygon s = new Polygon();
      s.readData(in);
      in.close();

      System.out.print("The second: ");
      System.out.println(s.getStart() + ", " + s.getEnd());
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
  }*/
}
//------------  Class Line ------------
class Line extends ProgrammZustand
{
  public Line()
  {
    super();
    zustand = LINE;
  }
  public Line(int sx, int sy, int ex, int ey)
  {
    super(sx, sy, ex, ey);
    zustand = LINE;
  }
  public boolean isContain(int x, int y)
{
    double c = Math.sqrt((endX-startX)*(endX-startX)+(endY-startY)*(endY-startY));
    double c1 = Math.sqrt((x-startX)*(x-startX)+(y-startY)*(y-startY));
    double c2 = Math.sqrt((endX-x)*(endX-x)+(endY-y)*(endY-y));

  if(c1+c2-c <= 2)
  {
    isSelected = true;
    return true;
  }
  else
  {
    isSelected = false;
    return false;
  }
}
}
//------------ Class Rectangle ------------
class Rectangle extends ProgrammZustand
{
  public Rectangle()
  {
    super();
    zustand = RECTANGLE;
  }
  public Rectangle(int sx, int sy, int ex, int ey)
  {
    super(sx, sy, ex, ey);
    zustand = RECTANGLE;
  }
  public boolean isContain(int x, int y)
  {
    if(x >= minX() && x <= maxX() && y >= minY() && y <= maxY())
    {
      isSelected = true;
      return true;
    }
    else
    {
      isSelected = false;
      return false;
    }
  }
}
//------------ Class Ellipse ------------
class Ellipse extends ProgrammZustand
{
  private double dx;  // MittelPunkt
  private double dy;
  private double a;   // L鋘ge a
  private double b;   // L鋘ge b
  public Ellipse()
  {
    super();
    zustand = ELLIPSE;
  }
  public Ellipse(int sx, int sy, int ex, int ey)
  {
    super(sx, sy, ex, ey);
    zustand = ELLIPSE;
  }
  public boolean isContain(int x, int y)
  {
    dx = (double) (startX+endX) / 2;
    dy = (double) (startY+endY) / 2;
    a = (double) (maxX()-minX()) / 2;
    b = (double) (maxY()-minY()) / 2;

    double x1 = (x-dx)*(x-dx) / (a*a);
    double y1 = (y-dy)*(y-dy) / (b*b);
    if(x1+y1 <= 1)
    {
      isSelected = true;
      return true;
    }
    else
    {
      isSelected = false;
      return false;
    }
  }
}
//------------ Class Circle ------------
class Circle extends ProgrammZustand
{
  private double dx;   // MittelPunkt
  private double dy;
  private double r;    // Radius

  public Circle()
  {
    super();
    zustand = CIRCLE;
  }
  public Circle(int sx, int sy, int ex, int ey)
  {
    super(sx, sy, ex, ey);
    zustand = CIRCLE;
  }
  public boolean isContain(int x, int y)
  {
    dx = (double) (startX+endX) / 2;
    dy = (double) (startY+endY) / 2;
    r = 0.5*Math.sqrt(Math.pow((endX-startX), 2));

    if((x-dx)*(x-dx)+(y-dy)*(y-dy)<=r*r)  //und temp.stored = false
    {
      isSelected = true;
      return true;
    }
    else
    {
      isSelected = false;
      return false;
    }
  }
}
//------------ Class Text ------------
class Text extends ProgrammZustand
{
  static String myText = " ";
  public Text()
  {
    super();
    super.text = new String();
    zustand = TEXT;
  }
  public Text(int sx, int sy, String theText)
  {
    super.startX = sx;
    super.startY = sy;
    super.isSelected = false;
    super.isFill = false;
    super.color = Color.BLACK;
    myText = theText;
    zustand = TEXT;
  }
  public void setText(String theText)
  {
   // super.startX = sx;
   // super.startY = sy;
    super.isSelected = false;
    super.isFill = false;
    super.color = Color.BLACK;
    myText = theText;
    zustand = TEXT;
  }
}
//------------ Class Raster ------------
class Raster extends ProgrammZustand
{
  static final int ABSTAND = 20;
  public Raster()
  {
    super();
    zustand = RASTER;
  }
}
//------------ Class ButtonPanel ------------
class ButtonPanel extends JPanel
{
  static int cnt = 0;
  public ButtonPanel()
  {
    JButton lineButton = new JButton("line");
    JButton rectangleButton = new JButton("rectangle");
    JButton ellipseButton = new JButton("ellipse");
    JButton circleButton = new JButton("circle");
    JButton textButton = new JButton("text");
    JButton move_or_eraseButton = new JButton("move_or_erase");
    JButton rasterButton = new JButton("raster");
    JButton colorButton = new JButton("color");
    add(lineButton);
    add(rectangleButton);
    add(ellipseButton);
    add(circleButton);
    add(textButton);
    add(move_or_eraseButton);
    add(rasterButton);
    add(colorButton);
    // lineButton:
    lineButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.lineButtonActived = true;
        PaintPanel.rectangleButtonActived = false;
        PaintPanel.ellipseButtonActived = false;
        PaintPanel.circleButtonActived = false;
        PaintPanel.textButtonActived = false;
        PaintPanel.move_or_eraseButtonActived = false;
        PaintPanel.currentShape = ProgrammZustand.LINE;
      }
    });
    // rectangleButton:
    rectangleButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.lineButtonActived = false;
        PaintPanel.rectangleButtonActived = true;
        PaintPanel.ellipseButtonActived = false;
        PaintPanel.circleButtonActived = false;
        PaintPanel.textButtonActived = false;
        PaintPanel.move_or_eraseButtonActived = false;
        PaintPanel.currentShape = ProgrammZustand.RECTANGLE;
      }
    });
    // ellipseButton:
    ellipseButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.lineButtonActived = false;
        PaintPanel.rectangleButtonActived = false;
        PaintPanel.ellipseButtonActived = true;
        PaintPanel.circleButtonActived = false;
        PaintPanel.textButtonActived = false;
        PaintPanel.move_or_eraseButtonActived = false;
        PaintPanel.currentShape = ProgrammZustand.ELLIPSE;
      }
    });
    // circleButton:
    circleButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.lineButtonActived = false;
        PaintPanel.rectangleButtonActived = false;
        PaintPanel.ellipseButtonActived = false;
        PaintPanel.circleButtonActived = true;
        PaintPanel.textButtonActived = false;
        PaintPanel.move_or_eraseButtonActived = false;
        PaintPanel.currentShape = ProgrammZustand.CIRCLE;
      }
    });
    // textButton:
    textButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.lineButtonActived = false;
        PaintPanel.rectangleButtonActived = false;
        PaintPanel.ellipseButtonActived = false;
        PaintPanel.circleButtonActived = false;
        PaintPanel.textButtonActived = true;
        PaintPanel.move_or_eraseButtonActived = false;
        PaintPanel.currentShape = ProgrammZustand.TEXT;
      }
    });
    // move_or_eraseButton:
    move_or_eraseButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.lineButtonActived = false;
        PaintPanel.rectangleButtonActived = false;
        PaintPanel.ellipseButtonActived = false;
        PaintPanel.circleButtonActived = false;
        PaintPanel.textButtonActived = false;
        PaintPanel.move_or_eraseButtonActived = true;
      }
    });
    // rasterButton:
    rasterButton.addActionListener( new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.rasterButtonActived = true;
        if(cnt == 0)
        {
          PaintPanel.rasterButtonActived = true;
          cnt = 1;
        }
        else
        {
          PaintPanel.rasterButtonActived = false;
          cnt = 0;
        }
      }
    });

    // colorButton:
    colorButton.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.colorButtonActived = true;
        Color defaultColor = Color.BLACK;
        Color selected = JColorChooser.showDialog(
            ButtonPanel.this, "Select Color", defaultColor);
        PaintPanel.currentColor = selected;
      }
    });
  }
}
//------------ PaintPanel ------------
class PaintPanel extends JPanel
{
  static int currentShape;
  static boolean currentFill;
  static Color currentColor;
  static Color currentBackColor;
  // f黵 Button Activit鋞e abzufragen
  static boolean lineButtonActived;
  static boolean rectangleButtonActived;
  static boolean ellipseButtonActived;
  static boolean circleButtonActived;
  static boolean textButtonActived;
  static boolean move_or_eraseButtonActived;
  static boolean rasterButtonActived;
  static boolean colorButtonActived;

  static boolean rasterEnabled;
  static boolean paintEnabled;
  static ArrayList polygon = new ArrayList();
  private static int moveX, moveY;
  private int currentX, currentY;

  public PaintPanel()
  {
    ///////////////////////////
    lineButtonActived = false;
    rectangleButtonActived = false;
    ellipseButtonActived = false;
    circleButtonActived = false;
    textButtonActived = false;
    move_or_eraseButtonActived = false;
    rasterButtonActived = false;

    ///////////////////////////
    paintEnabled = false;
    rasterEnabled = false;
    currentFill = false;
    currentColor = Color.BLACK;
    currentBackColor = Color.WHITE;

    polygon.ensureCapacity(20);

    setLayout(new BorderLayout());
    ButtonPanel buttonPanel = new ButtonPanel();
    add(buttonPanel, BorderLayout.NORTH);
    LabelPanel label = new LabelPanel();
    add(label, BorderLayout.SOUTH);
    
    addKeyListener(new MyKeyListener());
    addMouseListener(new MouseHandler());
    addMouseMotionListener(new MouseMotionHandler());
    //super.addKeyListener(new KeyHandler());

    setFocusable(true);
    requestFocus();
  }

  public void paintComponent(Graphics g)
  {
    paintEnabled = lineButtonActived || rectangleButtonActived
      || ellipseButtonActived || circleButtonActived || textButtonActived;
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;

    int w = getWidth();
    int h = getHeight();

    Rectangle2D scale = new Rectangle2D.Double(0, 0, w, h);
    g2.setColor(currentBackColor);
    g2.fill(scale);

    if(rasterButtonActived)
    {
      g2.setColor(Color.LIGHT_GRAY);
      for(int i = 1; i<=w; i += Raster.ABSTAND)
        g2.drawLine(i,0,i,h);
      for(int j = 1; j<=h; j += Raster.ABSTAND)
        g2.drawLine(0,j,w,j);
    }
    if(textButtonActived)
    {
      this.addKeyListener(new MyKeyListener());
    }

    for(int i=0; i<polygon.size(); i++)
    {
      ProgrammZustand temp = (ProgrammZustand)polygon.get(i);
      boolean fill = temp.isFill;
      g2.setColor(temp.color);
      switch(temp.zustand)
      {
        case ProgrammZustand.LINE:
          Line2D showLine = new Line2D.Double(temp.getStart(), temp.getEnd());
          g2.draw(showLine);
          break;
        case ProgrammZustand.RECTANGLE:
          Rectangle2D showSquare = new Rectangle2D.Double();
          showSquare.setFrameFromDiagonal(temp.getStart(), temp.getEnd());
          if(fill)
            g2.fill(showSquare);
          else
            g2.draw(showSquare);
          break;
        case ProgrammZustand.ELLIPSE:
          Ellipse2D showEllipse = new Ellipse2D.Double();
          showEllipse.setFrameFromDiagonal(temp.getStart(), temp.getEnd());
          if(fill)
            g2.fill(showEllipse);
          else
            g2.draw(showEllipse);
          break;
        case ProgrammZustand.CIRCLE:
          int xStart = (int)temp.getStart().getX();
          int yStart = (int)temp.getStart().getY();
          int circleWidth = (int)(temp.getEnd().getX()-temp.getStart().getX());
          if(circleWidth>0)
          {
            if (fill)
              g.fillOval( (int) temp.getStart().getX(),
                         (int) temp.getStart().getY(),
                         (int) (temp.getEnd().getX() - temp.getStart().getX()),
                         (int) (temp.getEnd().getX() - temp.getStart().getX()));
            else
              g.drawOval( (int) temp.getStart().getX(),
                         (int) temp.getStart().getY(),
                         (int) (temp.getEnd().getX() - temp.getStart().getX()),
                         (int) (temp.getEnd().getX() - temp.getStart().getX()));
            temp.setStart(xStart, yStart);
            temp.setEnd(xStart+circleWidth, yStart+circleWidth);
         }
         break;
        case ProgrammZustand.TEXT:
          String myText = temp.text;
          g.drawString(myText, (int)temp.getStart().getX(), (int)temp.getStart().getY());
          break;
      }
    }
  }
  private class LabelPanel extends JPanel
  {
    JLabel label;
    public LabelPanel()
    {
      label = new JLabel("Current X: " + currentX
                         + "  Current Y: " + currentY);
      add(label);
    }
    public void paintComponent(Graphics g)
    {
      super.paintComponent(g);
      label.setText("Current X: " + currentX
                    + "  Current Y: " + currentY);
    }
  }
  private class MouseHandler extends MouseAdapter
  {
    final int LMOUSE = 1;
    final int RMOUSE = 3;
    int mouseTyp;
    public void mousePressed(MouseEvent event)
    {
      int tempX, tempY;
      ProgrammZustand temp;
      tempX = event.getX();
      tempY = event.getY();
      currentX = tempX;
      currentY = tempY;

      mouseTyp = event.getButton();
      int isLeft = event.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK;
      int isRight = event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK;
      // right mouse tipped and move_or_erase Button actived
      // the figur will be removed.
      if(mouseTyp == RMOUSE && move_or_eraseButtonActived )
      {
        for(int i=0; i<polygon.size(); i++)
        {
          temp = (ProgrammZustand)polygon.get(i);
          if(temp.isContain(tempX, tempY))
          {
            polygon.remove(i);
            repaint();
            i--;
          }
        }
        repaint();
      }
      else if(mouseTyp == RMOUSE && paintEnabled)
      {
        currentX = event.getX();
        currentY = event.getY();
        repaint();
      }
      // left mouse and paintEnabled, should create the
      // approciated figur
      else if(mouseTyp == LMOUSE && paintEnabled)
      {
        switch(currentShape)
        {
          case ProgrammZustand.LINE:
            temp = new Line();
            break;
          case ProgrammZustand.RECTANGLE:
            temp = new Rectangle();
            break;
          case ProgrammZustand.ELLIPSE:
            temp = new Ellipse();
            break;
          case ProgrammZustand.CIRCLE:
            temp = new Circle();
            break;
          case ProgrammZustand.TEXT:
            temp = new Text();
            break;
          default:
            temp = new Rectangle();
        }
        temp.setStart(tempX, tempY);
        temp.color = currentColor;
        temp.isFill = currentFill;
        polygon.add(temp);
      }
      // bei Bewegung wird immer alte Position ermittelt

      else if(mouseTyp == LMOUSE && move_or_eraseButtonActived)
      {
        for(int i=0; i<polygon.size(); i++)
        {
          temp = (ProgrammZustand) polygon.get(i);
          if(temp.isContain(tempX, tempY))
          {
            //temp.isSelected = true;
            //temp.isStored = true;
            moveX = tempX;
            moveY = tempY;
            break;
          }
        }
        repaint();
      }
      repaint();
    }
    public void mouseReleased(MouseEvent event)
    {
      int tempX, tempY;
      ProgrammZustand temp;
      tempX = event.getX();
      tempY = event.getY();
      currentX = tempX;
      currentY = tempY;

      mouseTyp = event.getButton();
      int isLeft = event.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK;

      if(mouseTyp == LMOUSE && paintEnabled)
      {
        temp = (ProgrammZustand) polygon.remove(polygon.size() - 1);
        temp.setEnd(tempX, tempY);
        polygon.add(temp);
        repaint();
      }
      else if(mouseTyp == LMOUSE && move_or_eraseButtonActived)
      {
        for(int i=0; i<polygon.size(); i++)
        {
          temp = (ProgrammZustand)polygon.get(i);
          if(temp.isFrozen)
          {
            temp = (ProgrammZustand)polygon.remove(i);
            int x1 = (int)temp.getStart().getX() + (tempX - moveX);
            int y1 = (int)temp.getStart().getY() + (tempY - moveY);
            int x2 = (int)temp.getEnd().getX() + (tempX - moveX);
            int y2 = (int)temp.getEnd().getY() + (tempY - moveY);
            temp.setStart(x1, y1);
            temp.setEnd(x2, y2);

            //move_or_eraseButtonActived = true;
            temp.isSelected = false;
            temp.isFrozen = false;
            polygon.add(i, temp);
            repaint();
            break;
          }
        }
      }
      repaint();
    }

  }
  private class MouseMotionHandler implements MouseMotionListener
  {
    final int LMOUSE = 1;
    final int RMOUSE = 3;
    int mouseTyp;

    public void mouseMoved(MouseEvent event)
    {
      currentX = event.getX();
      currentY = event.getY();
      repaint();
    }

    public void mouseDragged(MouseEvent event)
    {
      int tempX, tempY;
      ProgrammZustand temp;

      tempX = event.getX();
      tempY = event.getY();
      currentX = tempX;
      currentY = tempY;
      mouseTyp = event.getButton();
      int isLeft = event.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK;
      int isRight = event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK;

      //wozu bin ich da :-)
      // wenn left mouse gehaltenden gedrueckt und bewegt
      // und wenn paintEnabled , dann soll ein Figur gezeichnet werden
      if(isLeft != 0 && paintEnabled)
      {
        /*
        for(int i = 0; i<polygon.size(); i++)
        {
          temp = (ProgrammZustand)polygon.get(i);
          if(temp.isContain(tempX, tempY)) //&& temp.isStored)
          {
            temp = (ProgrammZustand)polygon.remove(i);
            temp.setEnd(tempX, tempY);
            polygon.add(temp);
          }

        }
        */
        int polygonSize = polygon.size();
        temp = (ProgrammZustand)polygon.remove(polygonSize-1);
        //if(temp.isStored)
        temp.setEnd(tempX, tempY);
        polygon.add(temp);
        repaint();
      }
      // und wenn left mouse gehaltenden gedrueckt und bewegt
      // und move_or_eraseButtonActived dann soll die selected Figur
      // bewegt werden
      else if((isLeft != 0) && move_or_eraseButtonActived)
      {
        for(int i=0; i<polygon.size(); i++)
        {
          temp = (ProgrammZustand)polygon.get(i);
          if(temp.isContain(tempX, tempY))
          {
            int x1 = (int)temp.getStart().getX() + (tempX - moveX);
            int y1 = (int)temp.getStart().getY() + (tempY - moveY);
            int x2 = (int)temp.getEnd().getX() + (tempX - moveX);
            int y2 = (int)temp.getEnd().getY() + (tempY - moveY);
            temp.setStart(x1, y1);
            temp.setEnd(x2, y2);
          }
        }
        moveX = tempX;
        moveY = tempY;
        repaint();
      }
      repaint();
    }
  }
  class MyKeyListener extends KeyAdapter
    {
    public void keyPressed(KeyEvent ke)
    {
      System.out.println("test");
      ProgrammZustand temp;
      if(textButtonActived)
      {
        int polygonSize = polygon.size();
        temp = (ProgrammZustand)polygon.remove(polygonSize-1);
        if(ke.getKeyCode() == KeyEvent.VK_ENTER)
          textButtonActived = false; // Texteingabe beenden
        else
        {
          if(ke.getKeyCode() != KeyEvent.VK_BACK_SPACE)
            temp.text += ke.getKeyChar(); // Taste an String h鋘gen
          else
           if (temp.text.length()>0)  //Backspace
             temp.text = temp.text.substring(0,temp.text.length()-1); //letzten Charakter l鰏chen
        }
        polygon.add(temp);
        repaint();
      }
    }
  }
  class KeyHandler extends KeyAdapter
  {
    public void keyPressed(KeyEvent e)
    {
      ProgrammZustand temp;
      if(textButtonActived)
      {
        int polygonSize = polygon.size();
        temp = (ProgrammZustand)polygon.remove(polygonSize-1);
        if(e.getKeyCode() == KeyEvent.VK_ENTER)
          textButtonActived = false; // Texteingabe beenden
        else
        {
          if(e.getKeyCode() != KeyEvent.VK_BACK_SPACE)
            temp.text += e.getKeyChar(); // Taste an String h鋘gen
          else
           if (temp.text.length()>0)  //Backspace
             temp.text = temp.text.substring(0,temp.text.length()-1); //letzten Charakter l鰏chen
        }
        polygon.add(temp);
        repaint();
      }
    }
  }
}
//------------ Class PaintFrame ------------
class PaintFrame extends JFrame
{
  public PaintFrame()
  {
    setTitle("Paint Board");
    setBounds(100, 100, 800, 400);

    JMenuBar menuBar = makeMenuBar();
    setJMenuBar(menuBar);

    PaintPanel panel = new PaintPanel();
    getContentPane().add(panel);
  }
  private JMenuBar makeMenuBar()
  {
    JMenuBar menuBar = new JMenuBar();

    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    menuBar.add(fileMenu);

    JMenuItem newItem = new JMenuItem("New", 'N');
    newItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
    newItem.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.polygon.clear();
        PaintPanel.currentBackColor = Color.WHITE;
        PaintPanel.currentColor = Color.BLACK;
        PaintPanel.currentFill = false;
        PaintPanel.paintEnabled = false;
        PaintPanel.move_or_eraseButtonActived = true;
      }
    });
    fileMenu.add(newItem);

    JMenuItem openItem = new JMenuItem("Open", 'O');
    openItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
    openItem.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.showOpenDialog(PaintFrame.this);
      }
    });
    fileMenu.add(openItem);

    JMenuItem saveItem = new JMenuItem("Save", 'O');
    saveItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
    saveItem.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.showSaveDialog(PaintFrame.this);
      }
    });

    fileMenu.add(saveItem);
    fileMenu.addSeparator();

    JMenuItem exitItem = new JMenuItem("Exit", 'x');
    exitItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));
    exitItem.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        System.exit(0);
      }
    });
    fileMenu.add(exitItem);

    JMenu editMenu = new JMenu("Edit");
    editMenu.setMnemonic('E');
    menuBar.add(editMenu);

    JMenuItem undoItem = new JMenuItem("Undo", new ImageIcon("undo.gif"));
    undoItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK));
    editMenu.add(undoItem);

    JMenuItem cutItem = new JMenuItem("Cut", new ImageIcon("cut.gif"));
    cutItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
    editMenu.add(cutItem);

    JMenuItem copyItem = new JMenuItem("Copy", new ImageIcon("copy.gif"));
    copyItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK));
    editMenu.add(cutItem);
    JMenuItem pasteItem = new JMenuItem("Paste", new ImageIcon("paste.gif"));
    pasteItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
    editMenu.add(pasteItem);

    JMenu setMenu = new JMenu("Settings");
    setMenu.setMnemonic('S');
    menuBar.add(setMenu);

    JMenuItem backItem = new JMenuItem("Background", 'B');
    backItem.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        Color defaultColor = Color.BLACK;
        Color selected =
            JColorChooser.showDialog(PaintFrame.this, "Select Color", defaultColor);
        PaintPanel.currentBackColor = selected;
      }
    });
    setMenu.add(backItem);

    ButtonGroup group = new ButtonGroup();
    JRadioButtonMenuItem draw = new JRadioButtonMenuItem("Draw", true);
    draw.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.currentFill = false;
      }
    });
    JRadioButtonMenuItem fill = new JRadioButtonMenuItem("Fill", false);
    fill.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        PaintPanel.currentFill = true;
      }
    });
    group.add(draw);
    group.add(fill);
    JMenu style = new JMenu("Style");
    style.add(draw);
    style.add(fill);
    setMenu.add(style);

    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic('H');
    menuBar.add(helpMenu);

    JMenuItem helpItem = new JMenuItem("Help", 'H');
    helpItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK));
    helpMenu.add(helpItem);

    JMenuItem aboutItem = new JMenuItem("About", 'A');
    aboutItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
    aboutItem.addActionListener(
        new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        JOptionPane.showMessageDialog(
            PaintFrame.this, "        JPaint  Version 0.1\n\n" +
            "Author :  jellen chang \nE-mail :  [email]jellen@126.com[/email]" +
            "\n Author : kaihua wu \nE-mail: [email]kaihua1@yahoo.com[/email]");
      }
    });
    helpMenu.add(aboutItem);
    return menuBar;
  }
}
//------------ Public Class ------------
public class Zeichnen
{
  public static void main(String[] args) throws Exception
  {
    PaintFrame frame = new PaintFrame();
    JFrame.setDefaultLookAndFeelDecorated(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
  }
}
 
B

Beni

Gast
Ich hab im MouseListener noch ein
Code:
((Component)event.getSource()).requestFocus();
eingefügt. Dann wird zumindest etwas abgefangen.
 

kai

Mitglied
Beni,
wo soll dieses Code eingesetzt werden? Kannst Du mir ein paar Code im Zusammenhang geben? Oder schicke mir das von Dir verbesserte Progamm per email schicken? mein Emailaddresse : kaihua1@yahoo.com
 
B

Beni

Gast
Sorry, ich sollte ein bisschen ausführlicher schreiben :roll:

Code:
 private class MouseHandler extends MouseAdapter
  {
    final int LMOUSE = 1;
    final int RMOUSE = 3;
    int mouseTyp;
    public void mousePressed(MouseEvent event)
    {
    	((Component)event.getSource()).requestFocus();
    	
      int tempX, tempY;
      ProgrammZustand temp;

Das hilft dir hoffentlich mehr.
 

kai

Mitglied
Beni,
gucke mal hier, :lol: :lol:

public void mousePressed(MouseEvent event)
{
((Component)(event.getSource())).requestFocus();
((Component)(event.getSource())).addKeyListener(new MyKeyListener()); // ich habe es hingefügt.
int tempX, tempY;
ProgrammZustand temp;


hahahahahahahaha, es scheint jetzt schon etwas.
 
Status
Nicht offen für weitere Antworten.
Ähnliche Java Themen
  Titel Forum Antworten Datum
berserkerdq2 Mein Rechteck hat 4 Seiten, ich soll je nach dem, welche Seite berührt wurde, etwas ausführen, wie prüfe ich das? AWT, Swing, JavaFX & SWT 12
E LayoutManager Welcher Layout-Mix löst mein Problem? AWT, Swing, JavaFX & SWT 3
R Swing Hat mein JFrame meinen Component? AWT, Swing, JavaFX & SWT 2
B JavaFX habe mein Problem fett markiert AWT, Swing, JavaFX & SWT 2
G Swing Wenn ich mein JFrame Fenster vergrößere die Inhalte anpassen AWT, Swing, JavaFX & SWT 1
Thallius Warum refrehsed mein JTable nicht? AWT, Swing, JavaFX & SWT 5
B JavaFX Wo liegt mein Gedankenfehler ??? KeyEvent geht nicht ... AWT, Swing, JavaFX & SWT 8
W Swing JScrollPane für mein Fenster AWT, Swing, JavaFX & SWT 4
S Oracle's neue Sicherheitseinstellungen zerstoeren mein Applet. Was tun? AWT, Swing, JavaFX & SWT 3
R JavaFX Mein SceneBuilder Projekt AWT, Swing, JavaFX & SWT 3
N LookAndFeel Wie kann ich mein eigenes LookAndFeel machen? AWT, Swing, JavaFX & SWT 6
J Swing Warum wird mein Jpeg nicht angezeigt? AWT, Swing, JavaFX & SWT 4
T SWT Warum ist mein 1.Tree Node selektiert? AWT, Swing, JavaFX & SWT 11
M Warum funktioniert mein Applet nicht? AWT, Swing, JavaFX & SWT 6
P AWT Wie kann mein listener den Inhalt eines anderen Textfelds ändern? AWT, Swing, JavaFX & SWT 10
C Swing Linux mag mein Swing-repaint() nicht... AWT, Swing, JavaFX & SWT 7
L Mein Kopf dreht sich... Brauche Hilfe beim GUI gestalten AWT, Swing, JavaFX & SWT 10
V Swing Mein swingender Pokertisch macht Probleme AWT, Swing, JavaFX & SWT 10
G LookAndFeel SwingUtilities.updateComponentTreeUI(frame) <- wie heißt mein Frame? AWT, Swing, JavaFX & SWT 5
hdi Swing JTable: Mein CellRenderer ist ein Performance-Killer? AWT, Swing, JavaFX & SWT 7
R Japaner koennen mein Programm nicht nutzen..? AWT, Swing, JavaFX & SWT 11
K Mein Informatikprojekt läuft aus dem Ruder Hilfe. F1 ^^ AWT, Swing, JavaFX & SWT 5
J SwingX-Demo - mein Waterloo AWT, Swing, JavaFX & SWT 9
hdi mein layout verählt sich komisch AWT, Swing, JavaFX & SWT 4
M4nuel Warum überlagert JDesktopPane mein JMenuBar? AWT, Swing, JavaFX & SWT 5
C Komme nicht an mein textfeld AWT, Swing, JavaFX & SWT 3
P JRadioButton in Schleife erstellen > wo liegt mein Fehler AWT, Swing, JavaFX & SWT 2
P Ignoriert mein setSize()? AWT, Swing, JavaFX & SWT 2
R JFilechooser: gewählte Datei in mein FileReader übergeben AWT, Swing, JavaFX & SWT 18
C Mein erstes kleines Swing-Projekt - Probleme AWT, Swing, JavaFX & SWT 8
K JTable - warum funktioniert mein CellRenderer nicht? AWT, Swing, JavaFX & SWT 9
V Verstehe mein Druckproblem nicht AWT, Swing, JavaFX & SWT 2
M Wo bleibt mein ScrollPane? AWT, Swing, JavaFX & SWT 3
G Mein JFrame aktualisiert sich nicht richtig AWT, Swing, JavaFX & SWT 3
P Warum braucht mein kleines Programm 20 MB Speicher? AWT, Swing, JavaFX & SWT 13
Q Mein erstes GUI - Probleme AWT, Swing, JavaFX & SWT 2
E warum wird mein bild nicht angezeigt? AWT, Swing, JavaFX & SWT 6
Z Look&Feel-Wechsel bringt mein GUI durcheinander AWT, Swing, JavaFX & SWT 5
P JTextfield Text durch Keylistener verändern AWT, Swing, JavaFX & SWT 4
N Keylistener & JComboBox AWT, Swing, JavaFX & SWT 5
B Swing JButton mit KeyListener AWT, Swing, JavaFX & SWT 3
H KeyListener funktioniert nicht AWT, Swing, JavaFX & SWT 1
Fridolin111 Der KeyListener Löst kein event aus AWT, Swing, JavaFX & SWT 6
B KeyListener auf JFrame reagiert nicht AWT, Swing, JavaFX & SWT 8
N Mit KeyListener ein rechteck zeichnen AWT, Swing, JavaFX & SWT 9
S Swing JPanel nimmt keinen KeyListener an AWT, Swing, JavaFX & SWT 7
P JPanel KeyListener hinzufügen AWT, Swing, JavaFX & SWT 8
B Swing KeyListener auf Container? AWT, Swing, JavaFX & SWT 1
T Event Handling KeyListener reagiert nicht AWT, Swing, JavaFX & SWT 10
K KeyListener ohne JFrame AWT, Swing, JavaFX & SWT 9
C Keylistener funktioniert nicht AWT, Swing, JavaFX & SWT 1
T KeyListener funktioniert nicht wenn ich ein JButton hinzufüge AWT, Swing, JavaFX & SWT 1
A Event Handling Muss ich 'KeyListener' tasuend mal zufügen? AWT, Swing, JavaFX & SWT 7
S mit keylistener frame schliessen AWT, Swing, JavaFX & SWT 8
S Keylistener reagiert bei Buttons nicht. AWT, Swing, JavaFX & SWT 8
S KeyListener funktioniert nicht AWT, Swing, JavaFX & SWT 2
R KeyListener in mehreren Panels AWT, Swing, JavaFX & SWT 5
V Tastatur KeyListener für mehrere Buttons AWT, Swing, JavaFX & SWT 1
J JLabel Visible setzen in KeyListener AWT, Swing, JavaFX & SWT 13
X KeyListener AWT, Swing, JavaFX & SWT 0
L KeyListener für JDialog AWT, Swing, JavaFX & SWT 7
N KeyListener funktioniert nicht richitg AWT, Swing, JavaFX & SWT 4
Z SnakeGame Schlange per KeyListener bewegen! AWT, Swing, JavaFX & SWT 10
T KeyListener AWT, Swing, JavaFX & SWT 2
GianaSisters JFrame mit JInternalFrames, Keylistener-Problem AWT, Swing, JavaFX & SWT 9
7 KeyListener tastatur temporär blockieren AWT, Swing, JavaFX & SWT 7
7 AWT problem: KeyListener/ test im Label umändern AWT, Swing, JavaFX & SWT 4
B SWT Problem: Wie kann man für jede TableColumn einen eigenen KeyListener registrieren. AWT, Swing, JavaFX & SWT 1
U Mouse + Keylistener AWT, Swing, JavaFX & SWT 12
K ActionListener mit KeyListener AWT, Swing, JavaFX & SWT 7
J JWindow und keylistener AWT, Swing, JavaFX & SWT 1
F JavaFX KeyListener zum Fenster öffnen/schließen AWT, Swing, JavaFX & SWT 9
A Swing KeyEvent mit KeyListener und KeyAdapter kürzer schreiben AWT, Swing, JavaFX & SWT 7
D JTextArea auf KeyListener Command AWT, Swing, JavaFX & SWT 6
C KeyListener AWT, Swing, JavaFX & SWT 5
Doopy Event Handling KeyListener funktioniert nach Restart nicht mehr AWT, Swing, JavaFX & SWT 7
S KeyListener geht nicht AWT, Swing, JavaFX & SWT 12
C Swing KeyListener in JPanel AWT, Swing, JavaFX & SWT 2
A KeyListener Button wechseln & Programm beenden AWT, Swing, JavaFX & SWT 4
M Frage zu KeyListener bzgl. JApplet AWT, Swing, JavaFX & SWT 3
H Bild mit KeyListener verschieben AWT, Swing, JavaFX & SWT 2
C JTextField KeyListener AWT, Swing, JavaFX & SWT 6
Y KeyListener, GUI Thread, repaint AWT, Swing, JavaFX & SWT 7
bluerob Fehler bei Wertübermittlung über KeyListener AWT, Swing, JavaFX & SWT 3
E Swing KeyListener implementieren AWT, Swing, JavaFX & SWT 12
P KeyListener reagiert nicht AWT, Swing, JavaFX & SWT 11
M KeyListener richtig implementieren AWT, Swing, JavaFX & SWT 3
T KeyListener AWT, Swing, JavaFX & SWT 4
R KeyListener in JWindow AWT, Swing, JavaFX & SWT 7
T BlueJ KeyListener AWT, Swing, JavaFX & SWT 7
Z KeyListener AWT, Swing, JavaFX & SWT 2
M Swing KeyListener in JTextfield AWT, Swing, JavaFX & SWT 4
C Swing KeyListener für JPanel funktioniert nicht AWT, Swing, JavaFX & SWT 8
VfL_Freak Swing KeyListener, um einen Dialog per ESC zu schließen AWT, Swing, JavaFX & SWT 6
A Keylistener reagiert nicht AWT, Swing, JavaFX & SWT 10
D Problem mit KeyListener AWT, Swing, JavaFX & SWT 2
J KeyListener um auf CTRL-Enter zu reagieren AWT, Swing, JavaFX & SWT 2
L Snake in Java KeyListener Problem AWT, Swing, JavaFX & SWT 30
B "globaler" KeyListener? AWT, Swing, JavaFX & SWT 3
B JTable TableHeader KeyListener AWT, Swing, JavaFX & SWT 4

Ähnliche Java Themen

Neue Themen


Oben