按下键后,绘制的对象不会清除前一个矩形

时间:2014-05-05 19:21:46

标签: java swing jframe paint keylistener

我的代码不会清除上一个矩形。我想通过使用getRect()然后在我的keyPressed()方法中使用repaint()来解决问题。

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.Icon;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;


public class Rectangle extends JFrame implements KeyListener{

private int height;
private int width;
private int x;
private int y;
private Graphics2D g2;



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

   JLabel label = new JLabel();


    setSize(1000,1000);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);


    label.addKeyListener(this);
    label.setFocusable(true);
    label.setOpaque(true);
    label.addKeyListener(this);
    this.add(label);
    setVisible(true);
    label.requestFocusInWindow();

}


public void keyPressed(KeyEvent e)
{   

    if (e.getKeyCode() == KeyEvent.VK_DOWN)
    {
        g2.clearRect(x, y, width, height);
        repaint();
        y = y + 5;
        repaint();
    }
    if (e.getKeyCode() == KeyEvent.VK_LEFT)
    {
        g2.clearRect(x, y, width, height);
        repaint();
        x = x - 5;
        repaint();
    }
    if (e.getKeyCode() == KeyEvent.VK_UP)
    {
        g2.clearRect(x, y, width, height);
        repaint();
        y = y - 5;
        repaint();
    }
    if (e.getKeyCode() == KeyEvent.VK_RIGHT)
    {
        g2.clearRect(x, y, width, height);
        x = x + 5;
        repaint();
    }
}


public void keyReleased(KeyEvent e) {}

public void keyTyped(KeyEvent e) {}




public void paint(Graphics g) {

    g2 = (Graphics2D) g;
    g2.drawRect(x, y, width, height);

}

}

测试方法:

public class Test {

public static void main(String[] args)
{
    Rectangle rectangle = new Rectangle(400,200,500,500);

}
}

2 个答案:

答案 0 :(得分:2)

  1. setVisible(true)应该是公开Rectangle(...中的最后一个代码行,因为您已将JComponent添加到已经可见的Swing GUI中。

  2. 默认情况下,
  3. JFrame无法专注于KeyEvent

  4. 默认情况下将JPanel放入JFrame&#39} CENTER区域:myFrame.add(myPanel)

  5. 覆盖getPreferredSize的{​​{1}},而非设置为JPanel尺寸;调整应该通过调用JFrame初始化。

  6. myFrame.pack()必须能够专注于接收JPanelKeyEvent;使用KeyBindings而不是在setFocusable(true)层次结构中寻找焦点。

  7. 覆盖JComponent的{​​{1}};第一个代码行应为paintComponent,否则将出现绘制工件。

答案 1 :(得分:0)

你能添加更多细节吗? 从我所看到的,你可能想要一个清晰的按钮&方法。