How do I draw a string in Java 2D?

The code snippet below show you how to draw a string using Graphics2D. The drawString() method accept the string to be drawn and their x and y coordinate. Here you can also see how to set the antialiasing mode using the setRenderingHint() method.

package org.kodejava.awt.geom;

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

public class DrawString extends JPanel {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Draw String Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new DrawString());
        frame.pack();
        frame.setSize(420, 300);
        frame.setVisible(true);
    }

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

        // Define rendering hint, font name, font style and font size
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(new Font("Segoe Script", Font.BOLD + Font.ITALIC, 40));
        g2.setPaint(Color.ORANGE);

        // Draw Hello World String
        g2.drawString("Hello World!", 50, 100);
    }
}

Run the snippet, and you’ll see the following screen:

Draw 2D String

Draw 2D String

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 set Cell border width and color in iText?

The following example show you how to set the cell’s border width and color attributes. We can set the width and color at once using the setBorderWidth() and setBorderColor(). Or you can set it individually for each side of the cell’s border. You can also set the background color of a cell using the setBackgroundColor() method.

package org.kodejava.itextpdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class TableCellBorderDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableCellBorder.pdf"));
            doc.open();

            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));
            cell1.setUseBorderPadding(true);

            // Setting cell's border width and color
            cell1.setBorderWidth(5f);
            cell1.setBorderColor(BaseColor.BLUE);
            table.addCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
            cell2.setUseBorderPadding(true);

            // Setting cell's background color
            cell2.setBackgroundColor(BaseColor.GRAY);

            // Setting cell's individual border color
            cell2.setBorderWidthTop(1f);
            cell2.setBorderColorTop(BaseColor.RED);
            cell2.setBorderColorRight(BaseColor.GREEN);
            cell2.setBorderColorBottom(BaseColor.BLUE);
            cell2.setBorderColorLeft(BaseColor.BLACK);
            table.addCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));
            cell3.setUseBorderPadding(true);

            // Setting cell's individual border width
            cell3.setBorderWidthTop(2f);
            cell3.setBorderWidthRight(1f);
            cell3.setBorderWidthBottom(2f);
            cell3.setBorderWidthLeft(1f);
            table.addCell(cell3);
            table.completeRow();

            doc.add(table);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

How do I set the colors of JTabbedPane tabs?

The example below demonstrates how to change the color of the tabs in JTabbedPane component. The JTabbedPane‘s methods that you can use the change foreground and background color are:

  • setForeground(Color color) for changing the foreground color of all tabs.
  • setBackground(Color color) for changing the background color of all tabs.
  • setForegroundAt(int index, Color color) for changing foreground color for a tab at defined index.
  • setBackgroundAt(int index, Color color) for changing the background color of a tab at a defined index.
package org.kodejava.swing;

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

public class TabbedPaneTabColor extends JPanel {
    public TabbedPaneTabColor() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TabbedPaneTabColor();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTabbedPane Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TabbedPaneTabColor::showFrame);
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        JTabbedPane pane = new JTabbedPane();
        pane.addTab("A Tab", new JPanel());
        pane.addTab("B Tab", new JPanel());
        pane.addTab("C Tab", new JPanel());
        pane.addTab("D Tab", new JPanel());

        // Set all tabs foreground color to black.
        pane.setForeground(Color.BLACK);

        // Set different background color for all tabs in
        // JTabbedPane. The color from the first to the last
        // tab will be red, green yellow and orange.
        pane.setBackgroundAt(0, Color.RED);
        pane.setBackgroundAt(1, Color.GREEN);
        pane.setBackgroundAt(2, Color.YELLOW);
        pane.setBackgroundAt(3, Color.ORANGE);

        this.add(pane, BorderLayout.CENTER);
    }
}

The image below shows the result of the code snippet above:

JTabbedPane Tabs Color Demo

How do I set the initial color of a JColorChooser?

To create an instance of a JColorChooser with a default or initial color such as Color.BLUE you can pass the Color object to the constructor of the JColorChooser component. The example below shows how to do it.

package org.kodejava.swing;

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

public class JColorChooserDefaultColor extends JFrame {
    public JColorChooserDefaultColor() throws HeadlessException {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JColorChooserDefaultColor().setVisible(true));
    }

    private void initializeUI() {
        setTitle("JColorChooser Demo");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Creates an instance of JColorChooser and set Color.BLUE
        // as the default selected color.
        JColorChooser jcc = new JColorChooser(Color.BLUE);

        getContentPane().add(jcc, BorderLayout.CENTER);
        this.pack();
    }
}

JColorChooser Initial Color