我试图在 Java 中实现的是能够通过另一种方法绘制随机形状,而不必从一开始就绘制这些形状(用户自己选择 x、y、w、h)
这是我到目前为止所拥有的:
public class Design extends JComponent {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
super.paintComponent(g);
}
public void drawRect(int xPos, int yPos, int width, int height) {
Graphics g = null;
g.drawRect(width, height, xPos, yPos);
}
}
正如您在上面所看到的,我编写了drawRect函数,但不明白如何制作它,因此当我调用drawRect()函数时,它会使用paint()函数来绘制一个矩形,这正是Paint 函数在其中输入 g.drawRect() 和 x,y,w,h。 我这样做而不是直接使用paint()的原因是因为我正在尝试创建一个组件,因此不必每次都键入paint()函数,我只需将此类添加到我的Swing中即可完成。
希望您理解我在这里想要实现的目标。 谢谢。
最佳答案
你需要做的第一件事就是放弃你可以控制绘制过程的想法,你不能,你可以响应绘制事件并向 RepaintManager 发出请求,可能需要更新。
基本上,您不会直接调用 paint
,而是调用 Paint 来响应 RepaintManager
想要绘制的内容。
看看Painting in AWT and Swing和 Performing Custom Painting 。
关于您的代码。不要覆盖paint
,当然也不要规避绘画过程,相反,它应该看起来更像这样......
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawRect(g, 10, 10, 10, 10);
}
protected void drawRect(Graphics g, int xPos, int yPos, int width, int height) {
g.drawRect(xPos, yPos, width, height);
}
Graphics#drawRect
实际上采用参数 x
、y
、width
、height
按此顺序...
The reason why I am doing this and not just straight up using paint() is because i'm trying to make a component so instead of having to type out the paint() function every time
没有意义,这就是拥有 paint
方法的要点,因此您可以自定义组件的绘制方式,创建它的大量实例并将其添加到您的 GUI...这就是所有 Swing 控件的工作方式...
此外,您可能会发现 2D Graphics感兴趣的
根据评论进行更新
因此,您需要一个其他对象可以调用的方法,并且该方法将使它们能够向现有对象/组件添加“矩形”...
首先定义 Rectangle
的实例变量
private Rectangle rectangle;
在您的 paintComponent
中,检查 rectangle
是否为 null
,如果不是,则绘制它...
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rectangle != null) {
Graphics2D g2d = (Graphics2D)g;
g2d.draw(rectangle);
}
}
现在,更新您的 drawRect
方法以创建一个实例 Rectangle
并请求重新绘制组件
public void drawRect(int xPos, int yPos, int width, int height) {
rectangle = new Rectangle(xPos, yPos, width, height);
repaint();
}
例如...
public class Design extends JComponent {
private Rectangle rectangle;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rectangle != null) {
Graphics2D g2d = (Graphics2D)g;
g2d.draw(rectangle);
}
}
public void drawRect(int xPos, int yPos, int width, int height) {
rectangle = new Rectangle(xPos, yPos, width, height);
repaint();
}
}
现在,如果您想支持多个矩形,您只需使用 List
并根据需要添加任意数量的 Rectangle
实例,迭代
paintComponent
方法中的列表
关于java - 从Java中的另一个方法调用paint(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24322484/