简单的Java 2D图形:绘制一个矩形?

时间:2014-02-23 05:53:55

标签: java swing

我正在尝试让Java 2D图形“hello world”继续进行,并且发现它非常困难(即,我正在使用Google搜索“java hello world示例”的变体并且空出来)。任何人都可以用最小的hellow世界示例来帮助我吗?

修改

这是一个很好的起点,"The Java Tutorials: Performing Custom Painting"

3 个答案:

答案 0 :(得分:13)

要在Swing中绘制一个矩形,你应该:

  • 首先,永远不要直接在JFrame或其他顶级窗口中绘图。
  • 而是在JPanel,JComponent或最终从JComponent扩展的其他类中绘制。
  • 您应该覆盖paintComponent(Graphics g)方法。
  • 您应该确保调用超级方法
  • 您应该使用JVM提供给方法的Graphics对象绘制矩形。
  • 你应该在Swing教程中阅读这幅画。

清除?

如,

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

public class DrawRect extends JPanel {
   private static final int RECT_X = 20;
   private static final int RECT_Y = RECT_X;
   private static final int RECT_WIDTH = 100;
   private static final int RECT_HEIGHT = RECT_WIDTH;

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      // draw the rectangle here
      g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT);
   }

   @Override
   public Dimension getPreferredSize() {
      // so that our GUI is big enough
      return new Dimension(RECT_WIDTH + 2 * RECT_X, RECT_HEIGHT + 2 * RECT_Y);
   }

   // create the GUI explicitly on the Swing event thread
   private static void createAndShowGui() {
      DrawRect mainPanel = new DrawRect();

      JFrame frame = new JFrame("DrawRect");
      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();
         }
      });
   }
}

答案 1 :(得分:3)

您需要创建一个从JComponent(或其子类之一,如下例中的JPanel)扩展的类,并覆盖paintComponent(Graphics g)。这是一个例子:

class MyPanel extends JPanel {

    private int squareX = 50;
    private int squareY = 50;
    private int squareW = 20;
    private int squareH = 20;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g); // do your superclass's painting routine first, and then paint on top of it.
        g.setColor(Color.RED);
        g.fillRect(squareX,squareY,squareW,squareH);
    }
}

答案 2 :(得分:1)

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g);
    g2.setColor(Color.red);
    g2.drawRect(10, 10, 100, 100);
}

enter image description here