0

我已经学习了一段时间的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()

4

1 回答 1

2

编辑我的错误:您没有正确设置颜色。以机智:

例如,

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));
   }
}
于 2013-11-06T03:01:12.650 回答