Java中的绘制矩形
问题描述 投票:-1回答:1
我正在尝试绘制一个矩形。但我不确定如何在特定面板上绘画。想看一个例子,我如何提供绘制矩形的面板和位置。我有以下模板,我想看看要使用该类在任何面板上绘制矩形需要进行哪些修改。我的意图是使用面板的宽度和高度,并在该位置添加一个矩形。目标是能够在任何具有JPanel的任何地方使用此类。import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawRectangle{
private int startX;
private int startY;
private int width;
private int height;
private Color color;
private JPanel panel;
public DrawRectangle(JPanel panel, int startX, int startY, int width, int height, Color color) {
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
this.color = color;
this.panel = panel;
}
public void paint(Graphics g) {
g.setColor(this.color);
g.fillRect(this.startX, this.startY, this.width, this.height);
g.drawRect(this.startX, this.startY, this.width, this.height);
}
}
java
swing
paintcomponent
1个回答
0
投票
您必须修改感兴趣的JPanel才能通过以下方式使用该代码:覆盖其paintComponent方法
首先在您的覆盖中调用上级的paintComponent方法
然后绘制您自己的DrawRectangle类的paint方法
如果您希望能够绘制多个矩形,则给JPanel一个ArrayList并在paintComponent的for循环中绘制它们。>
例如,对于一个矩形:public class DrawingPanel extends JPanel {
private DrawRectangle drawRectangle;
public DrawingPanel(DrawRectangle drawRectangle) {
this.drawRectangle = drawRectangle;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (drawRectangle != null) {
drawRectangle.paint(g);
}
}
}
并且对于许多矩形:public class DrawingManyRectPanel extends JPanel {
private List drawRectangles;
public DrawingManyRectPanel(List drawRectangles) {
this.drawRectangles = drawRectangles;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (drawRectangles != null) {
for (DrawRectangle rectangle : drawRectangles) {
rectangle.paint(g);
}
}
}
}
在这些类中,重写了构造函数,以允许通过构造函数调用将矩形注入到该类中。对于第二个类,我还将添加一个方法,该方法允许添加其他矩形:public void addRectangle(DrawRectangle rectangle) {
drawRectangles.add(rectangle);
repaint();
}
类似于删除矩形
热门问题