How do I draw a round rectangle in Java 2D?

The RoundRectangle2D class defines a rectangle with rounded corners defined by a location (x,y), dimension (w x h), and the width and height of an arc with which to round the corners.

The RoundRectangle2D.Double class constructs a RoundRectangle2D from the specified values in double, including the location, width and the arch of the round rectangle.

package org.kodejava.awt.geom;

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

public class DrawRoundRectangle extends JComponent {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Rounded Rectangle Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DrawRoundRectangle(), BorderLayout.CENTER);
        frame.pack();
        frame.setSize(420, 300);
        frame.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setPaint(Color.RED);
        g2.setStroke(new BasicStroke(2.0f));

        double x = 50;
        double y = 50;
        double w = x + 250;
        double h = y + 100;
        g2.draw(new RoundRectangle2D.Double(x, y, w, h, 50, 50));
    }
}

Here is the result you’ll get when you run the snippet:

Draw 2D Round Rectangle

Draw 2D Round Rectangle

How do I draw a rectangle in Java 2D?

The code snippet below show you how to use the Graphics2D class the draw a rectangle. You can see the snippet in the paintComponent(Graphics g) method defined in the anonymous JPanel object.

To draw a rectangle we use the Rectangle2D.Double static-inner class. The constructor of this class accept the information about the rectangle x, y coordinates and its width and height.

package org.kodejava.awt.geom;

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

public class DrawRectangle {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Draw Rectangle");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.add(new JPanel() {
                @Override
                protected void paintComponent(Graphics g) {
                    // Draw a rectangle using Rectangle2D class
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setColor(Color.RED);

                    double x = 100;
                    double y = 100;
                    double width = x + 200;
                    double height = y + 50;

                    // Draw the red rectangle
                    g2.draw(new Rectangle2D.Double(x, y, width, height));

                    g2.setColor(Color.BLUE);
                    // Draw the blue rectangle
                    g2.draw(new Rectangle2D.Double(150, 50, 200, 250));
                }
            }, BorderLayout.CENTER);

            frame.pack();
            frame.setSize(new Dimension(500, 400));
            frame.setVisible(true);
        });
    }
}

Here is the result you’ll get when you run the snippet:

Draw 2D Rectangle

Draw 2D Rectangle

How do I draw a line in Java 2D?

The following code snippet show you how to draw a simple line using Graphics2D.draw() method. This method take a parameter that implements the java.awt.Shape interface.

To draw a line we can use the Line2D.Double static-inner class. This class constructor takes four integers values that represent the start (x1, y1) and end (x2, y2) coordinate of the line.

package org.kodejava.awt.geom;

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

public class DrawLine extends JComponent {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Line");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DrawLine());
        frame.pack();
        frame.setSize(new Dimension(420, 440));
        frame.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        // Draw a simple line using the Graphics2D draw() method.
        Graphics2D g2 = (Graphics2D) g;
        g2.setStroke(new BasicStroke(2f));
        g2.setColor(Color.RED);
        g2.draw(new Line2D.Double(50, 150, 250, 350));
        g2.setColor(Color.GREEN);
        g2.draw(new Line2D.Double(250, 350, 350, 250));
        g2.setColor(Color.BLUE);
        g2.draw(new Line2D.Double(350, 250, 150, 50));
        g2.setColor(Color.YELLOW);
        g2.draw(new Line2D.Double(150, 50, 50, 150));
        g2.setColor(Color.BLACK);
        g2.draw(new Line2D.Double(0, 0, 400, 400));
    }
}

When you run the snippet it will show you something like:

Draw 2D Line

Draw 2D Line

How do I read file using FileInputStream?

The following example use the java.io.FileInputStream class to read contents of a text file. We’ll read a file located in the temporary directory defined by operating system. This temporary directory can be accessed using the java.io.tmpdir system property.

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        // Get the temporary directory. We'll read the data.txt file
        // from this directory.
        String tempDir = System.getProperty("java.io.tmpdir");
        File file = new File(tempDir + "/data.txt");

        StringBuilder builder = new StringBuilder();
        FileInputStream fis = null;
        try {
            // Create a FileInputStream to read the file.
            fis = new FileInputStream(file);

            int data;
            // Read the entire file data. When -1 is returned it
            // means no more content to read.
            while ((data = fis.read()) != -1) {
                builder.append((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // Print the content of the file
        System.out.println("File Contents = " + builder);
    }
}

The content read from the input stream will be appended into a StringBuilder object. At the end of the snippet the content of the will be converted into string using the toString() method.

Here are the content of our data.txt file.

File Contents = Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

How do I convert string to Date in GMT timezone?

The following code snippet convert a string representation of a date into a java.util.Date object and the timezone is set to GMT. To parse the string so that the result is in GMT you must set the TimeZone of the DateFormat object into GMT.

package org.kodejava.joda;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class WithTimezoneStringToDate {
    public static void main(String[] args) {
        // Create a DateFormat and set the timezone to GMT.
        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));

        try {
            // Convert string into Date
            Date today = df.parse("Fri, 29 Oct 2021 00:00:00 GMT+08:00");
            System.out.println("Today = " + df.format(today));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above print the following output:

Today = Thu, 28 Oct 2021 16:00:00 GMT