我学习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));
}
}