gpt4 book ai didi

java - 按下按键后绘制的对象不会清除先前的矩形

转载 作者:行者123 更新时间:2023-12-02 05:51:41 25 4
gpt4 key购买 nike

我的代码不会清除之前的矩形。我认为通过使用 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);

}
}

最佳答案

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

  2. 默认情况下,JFrame 对于 KeyEvent 无法获得焦点。

  3. JPanel放到JFrameCENTER区域,默认:myFrame.add(myPanel).

  4. 覆盖 JPanelgetPreferredSize,而不是设置 JFrame 大小;应通过调用 myFrame.pack() 来初始化大小。

  5. JPanel 必须可聚焦才能接收 KeyEventsetFocusable(true);使用 KeyBindings 而不是在 JComponent 层次结构中寻找焦点。

  6. 覆盖JPanelpaintComponent;第一个代码行应该是 super.paintComponent,否则会出现绘画伪像。

关于java - 按下按键后绘制的对象不会清除先前的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com