当我按其中一个箭头键时,我的代码不会清除前一个矩形。我认为在我的repaint()
方法中使用keyPressed()
可以解决问题。我也尝试使用clearRect()
,但这没有做任何事情。
这是空闲的矩形:
这是当我按住右箭头键时:
这是我的代码:
import java.awt.Component;
import java.awt.Dimension;
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;
import javax.swing.JPanel;
public class Rectangle extends JPanel 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();
label.addKeyListener(this);
label.setFocusable(true);
label.setOpaque(true);
label.addKeyListener(this);
this.add(label);
label.requestFocusInWindow();
setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
y = y + 5;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
x = x - 5;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_UP)
{
y = y - 5;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
x = x + 5;
repaint();
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void paintComponent(Graphics g) {
this.g2 = (Graphics2D) g;
g2.drawRect(x, y, width, height);
}
}
测试课
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Rectangle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add( new Rectangle(40,20,250,250));
f.pack();
f.setVisible(true);
}
}
答案 0 :(得分:1)
您错过了添加super.paintComponent(g);
正在打破流量的行为。
通过单行更改,您可以正常使用代码。
public void paintComponent(Graphics g) {
super.paintComponent(g); // add this line
this.g2 = (Graphics2D) g;
g2.drawRect(x, y, width, height);
}
请详细了解Painting in AWT and Swing
答案 1 :(得分:0)
我可以用其他方式思考,你不必绘制父组件。
在致电drawRect之前,您可以清除呼叫clearRect的旧呼叫。您必须保存当前矩形的尺寸和位置。