setVisible(true)
should be last code line in publicRectangle(...
, because you addedJComponent
s to the already visible Swing GUI.JFrame
isn't focusable forKeyEvent
, by default.put
JPanel
toJFrame
'sCENTER
area, by default:myFrame.add(myPanel)
.override
getPreferredSize
forJPanel
instead of setting forJFrame
size; sizing should be intialized by callingmyFrame.pack()
.JPanel
must be focusable for receiving anKeyEvent
,setFocusable(true)
; use KeyBindings instead of hunting for focus inJComponent
hierarchy.override
paintComponent
forJPanel
; 1st code line should besuper.paintComponent
, otherwise painting artifacts will occur.
Drawn object doesn't clear previous rectangle after key is pressed
-
16-07-2023 - |
Вопрос
My code will not clear the previous rectangle. I thought by using the getRect() and then using repaint() in my keyPressed() method, that would solve the problem.
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);
}
}
Test Method:
public class Test {
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle(400,200,500,500);
}
}
Решение
Другие советы
Could you add more detail? From what I can see, you may want to make a clear button & method.
Не связан с StackOverflow