Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java 2D graphics: draw a rectangle? [closed]

Tags:

java

swing

I'm trying to get a Java 2D graphics "hello world" going, and am finding it strangely difficult (ie, I'm Googling variations of "java hello world example" and coming up empty). Can anyone help me with a minimal hellow world example?

Edit

This is a good starting point though, "The Java Tutorials: Performing Custom Painting".

like image 633
McGarnagle Avatar asked Feb 23 '14 05:02

McGarnagle


1 Answers

To draw a rectangle in Swing you should:

  • First of all, never draw directly in the JFrame or other top-level window.
  • Instead draw in a JPanel, JComponent or other class that eventually extends from JComponent.
  • You should override the paintComponent(Graphics g) method.
  • You should be sure to call the super method
  • You should draw your rectangle with the Graphics object provided to the method by the JVM.
  • You should read the painting in Swing tutorial.

Clear?

e.g.,

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();
         }
      });
   }
}
like image 85
Hovercraft Full Of Eels Avatar answered Oct 13 '22 12:10

Hovercraft Full Of Eels