【发布时间】:2020-10-30 13:59:39
【问题描述】:
所以基本上我正在尝试向 JPanel 添加一些矩形。这个特定的 Rectangle 也有改变可见性和颜色的方法。但是当添加这些矩形时,什么也没有发生。
这是 Rectangles 的类:
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
public class Rectangle extends JPanel {
private int x;
private int y;
private static int Width = 30;
private static int Height = 30;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new java.awt.Color(0, 102, 0));
g.drawRect(x, y, Width, Height);
}
public Rectangle(int x, int y) {
this.x = x;
this.y = y;
}
public void changeColor() {
setBackground(new java.awt.Color(0, 102, 0));
repaint();
}
public void changeVisibility() {
setVisible(false);
}
}
这是在 Frame 类中将 Recangles 添加到 JPanel 的方法:
public void placeRectangle(int x, int y) {
Rectangle newRect = new Rectangle(x, y);
panel.add(newRasenblock);
newRect.setVisible(true);
}
我之前用矩形测试过这个方法(没有changeColor 和changeVisibility),它在那里工作,但在这里有类似的代码,突然不行。
【问题讨论】:
-
您不应该在您的方法中添加
newRect吗?newRasenblock是什么?如果您展示一个调用该方法的简单示例,也会有所帮助。 -
发布正确的minimal reproducible example 来演示问题。另外,不要将您的类称为“矩形”,因为该名称有一个 AWT 类,因此会造成混淆。您的班级名称应该更具体。
-
注意,当您在paintComponent 内部调用
drawRect时,坐标将相对于JPanel 所在的位置。所以如果你希望你的 JPanel 是矩形的大小,那么 drawRect 应该是 (0,0)。
标签: java rectangles