gpt4 book ai didi

java - 矩形未在 BufferedImage 上绘制

转载 作者:行者123 更新时间:2023-12-02 06:34:22 25 4
gpt4 key购买 nike

我学习java有一段时间了,我刚刚开始一个项目来制作一个功能性绘图程序。然而,下面的代码应该在缓冲图像上绘制一个矩形,但它不起作用。

绘制矩形的代码

public class DrawRectangle extends Panel {

public void drawRect(int x, int y, int width, int height) {
System.out.println("new Rectangle = X:" + x + " Y:" + y + " Width:" + width + " height:" + height);
canvas.createGraphics().draw(new Rectangle2D.Double(x, y, width, height));
}}



public class Panel extends JPanel {

BufferedImage canvas = new BufferedImage(400,400, BufferedImage.TYPE_INT_ARGB);

......

public void paintComponent(Graphics g) {
super.paintComponent(g);

System.out.println("Repainting");

g.drawImage(canvas, 25, 25, null);

}}

注意:所有方法都正确执行,因此不仅仅是我忽略了启动drawRectangle()

最佳答案

编辑我的缺点:你没有正确设置颜色。也就是说:

例如,

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;

public class FunnyDraw {

private static void createAndShowGui() {
DrawRectangle mainPanel = new DrawRectangle();
mainPanel.drawRect(10, 10, 100, 100);
mainPanel.betterDrawRect(200, 200, 200, 200);

JFrame frame = new JFrame("FunnyDraw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

class HisPanel extends JPanel {

private static final Color COLOR = Color.black;
private static final int PREF_W = 600;
private static final int PREF_H = 450;
protected BufferedImage canvas = new BufferedImage(PREF_W, PREF_H,
BufferedImage.TYPE_INT_ARGB);

public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Repainting");
g.drawImage(canvas, 25, 25, null);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}

public void draw(Shape shape) {
Graphics2D g2 = canvas.createGraphics();
g2.setColor(COLOR);
g2.draw(shape);
g2.dispose();
repaint();
}
}

class DrawRectangle extends HisPanel {

public void drawRect(int x, int y, int width, int height) {
Graphics2D g2 = canvas.createGraphics();
g2.setColor(Color.black);
g2.draw(new Rectangle2D.Double(x, y, width, height));
g2.dispose();
repaint();
}

public void betterDrawRect(int x, int y, int width, int height) {
draw(new Rectangle2D.Double(x, y, width, height));
}
}

关于java - 矩形未在 BufferedImage 上绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803276/

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