How to define JRadioButton label position?

In this code snippet you’ll see how to define JRadioButton label position.┬áBy default the label will be displayed on the right side of the button. In the code below you will see some examples for placing the label on the left side, at the top and the bottom of the JRadioButton.

To define the label position we use the combination of the setHorizontalTextPosition() and setVerticalTextPosition() method and specified the position using one of the available constant in SwingConstants interface.

package org.kodejava.example.swing;

import javax.swing.*;

public class RadioButtonLabelPosition {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();

        // Create JRadioButton with label on the right
        JRadioButton button1 = new JRadioButton("Button One");
        button1.setHorizontalTextPosition(SwingConstants.RIGHT);

        // Create JRadioButton with label on the left
        JRadioButton button2 = new JRadioButton("Button Two");
        button2.setHorizontalTextPosition(SwingConstants.LEFT);

        // Create JRadioButton with label at the bottom centered.
        JRadioButton button3 = new JRadioButton("Button Three");
        button3.setVerticalTextPosition(SwingConstants.BOTTOM);
        button3.setHorizontalTextPosition(SwingConstants.CENTER);

        // Create JRadioButton with label at the top centered.
        JRadioButton button4 = new JRadioButton("Button Four");
        button4.setVerticalTextPosition(SwingConstants.TOP);
        button4.setHorizontalTextPosition(SwingConstants.CENTER);

        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);

        frame.add(panel);
        frame.setSize(300, 300);
        frame.pack();
        frame.setVisible(true);
    }
}

Here is a screen capture result of the code snippet above:

JRadioButton Label Position

How do I flash the window taskbar in Swing?

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class WindowTaskbarFlash extends JFrame {
    public WindowTaskbarFlash() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setSize(200, 200);
        setState(Frame.ICONIFIED);

        // Demonstrate flashes the application window task bar
        // by calling the toFront method every 5 seconds.
        Timer timer = new Timer(5000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                toFront();
            }
        });
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new WindowTaskbarFlash().setVisible(true);
            }
        });
    }
}

How do I change JFrame state programmatically?

In the following code snippet you’ll learn how to programmatically change the frame state of a JFrame component in a Swing application. The JFrame states are represented as a bitwise masks. You can minimize, maximize or make the JFrame state to normal using the JFrame.setExtendedState() method.

You can pass the following values as the parameter to the method:

  • Frame.NORMAL
  • Frame.ICONIFIED
  • Frame.MAXIMIZED_HORIZ
  • Frame.MAXIMIZED_VERT
  • Frame.MAXIMIZED_BOTH
package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingFrameState extends JFrame {
    public SwingFrameState() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        final JButton minimize = new JButton("Minimize");
        final JButton maximize = new JButton("Maximize");
        final JButton normal = new JButton("Normal");

        add(normal);
        add(minimize);
        add(maximize);

        pack();
        setSize(200, 200);

        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == normal) {
                    setExtendedState(Frame.NORMAL);                    
                } else if (e.getSource() == minimize) {
                    setExtendedState(Frame.ICONIFIED);
                } else if (e.getSource() == maximize) {
                    setExtendedState(Frame.MAXIMIZED_BOTH);
                }
            }
        };

        minimize.addActionListener(listener);
        maximize.addActionListener(listener);
        normal.addActionListener(listener);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SwingFrameState().setVisible(true);
            }
        });
    }
}

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.example.awt.geom;

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

public class DrawString extends JPanel {
    @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(Font.SERIF, Font.ITALIC, 40));
        g2.setPaint(Color.BLUE);
       
        //
        // Draw Hello World String
        //
        g2.drawString("Hello World!", 100, 100);
    }

    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(400, 300);
        frame.setVisible(true);
    }
}

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

Draw String Demo

How do I draw a vertical text in Java 2D?

To draw a text / string vertically we need to do a transform on the Graphics2D object. First, create an instance of AffineTransform and set the rotation using the setToRotation() method. And then pass this transform object into g2.setTransform() method.

package org.kodejava.example.awt.geom;

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

public class DrawVerticalText extends JPanel {
    @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(Font.SERIF, Font.BOLD, 20));

        //
        // Rotate 90 degree to make a vertical text
        //
        AffineTransform at = new AffineTransform();
        at.setToRotation(Math.toRadians(90), 10, 10);
        g2.setTransform(at);
        g2.drawString("This is a vertical text", 10, 10);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Draw Vertical Text Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new DrawVerticalText());
        frame.pack();
        frame.setSize(200, 300);
        frame.setVisible(true);
    }
}

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

Draw Vertical Text Demo

How do I create a gradient paint in Java 2D?

To change the color of a graphics shape we can use the setPaint() method. For a simple coloring we can pass the color object into this method, such as Color.RED or Color.GREE.

If you want to paint with a gradient paint you can use the GradientPaint class. This class provides a way to fill a shape with a linear color gradient pattern. To create a gradient color pattern you can pass the following parameter to the object constructor.

  • x1: x coordinate of the first specified point in user space
  • y1: y coordinate of the first specified point in user space
  • color1: color at the first specified point
  • x2: x coordinate of the second specified point in user space
  • y2: y coordinate of the second specified point in user space
  • color2: color at the second specified point

package org.kodejava.example.awt.geom;

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

public class GradientPaintDemo extends JApplet {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        GradientPaint blackToGray = new GradientPaint(50, 50, Color.BLACK,
                300, 100, Color.LIGHT_GRAY);
        g2.setPaint(blackToGray);
        g2.fill(new Rectangle2D.Double(50, 50, 300, 100));

        GradientPaint blueToBlack = new GradientPaint(0, 0, Color.BLUE,
                400, 400, Color.BLACK);
        g2.setPaint(blueToBlack);
        g2.fill(new Rectangle2D.Double(50, 160, 300, 100));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Gradient Paint Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new GradientPaintDemo();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 350));
        frame.setVisible(true);
    }
}

This code snippet produce the following output:

Gradient Paint Demo

How do I define stroke when drawing a shape in Java 2D?

package org.kodejava.example.awt.geom;

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

public class DrawStrokeDemo extends JApplet {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
       
        float[] strokes = {1, 2, 3, 4, 5, 6};
        for (float stroke : strokes) {
            g2.setStroke(new BasicStroke(stroke));
            g2.draw(new Line2D.Float(50, stroke * 20, 350, stroke * 20));
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Stroke Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new DrawStrokeDemo();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 200));
        frame.setVisible(true);
    }
}

This code snippet produce the following output:

Draw Stroke Demo

How do I create a dashed stroke in Java 2D?

package org.kodejava.example.awt.geom;

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

public class DrawDashedStroke extends JApplet {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        float[] dash = {10.0f, 5.0f, 3.0f};

        //
        // Creates a dashed stroke
        //
        Stroke dashed = new BasicStroke(2.0f, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);

        g2.setStroke(dashed);
        g2.setPaint(Color.RED);
        g2.draw(new RoundRectangle2D.Double(50, 50, 300, 100, 10, 10));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Dashed Stroke Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new DrawDashedStroke();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 250));
        frame.setVisible(true);
    }
}

This code snippet produce the following output:

Draw Dashed Stroke Demo

How do I draw an arc in Java 2D?

Arc2D is the abstract superclass for all objects that store a 2D arc defined by a framing rectangle, start angle, angular extent (length of the arc), and a closure type
(Arc2D.OPEN, Arc2D.CHORD, or Arc2D.PIE).

To constructs a new arc in double values, such as defining the specified location, size, angular extents, and closure type we can use the Arc2D.Double static-inner class.

package org.kodejava.example.awt.geom;

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

public class DrawArc extends JApplet {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setStroke(new BasicStroke(2.0f));
        g2.setPaint(Color.RED);
        g2.draw(new Arc2D.Double(50, 50, 300, 300, 0, 90, Arc2D.PIE));
        g2.setPaint(Color.GREEN);
        g2.draw(new Arc2D.Double(50, 50, 300, 300, 90, 90, Arc2D.PIE));
        g2.setPaint(Color.BLUE);
        g2.fill(new Arc2D.Double(50, 50, 300, 300, 180, 90, Arc2D.PIE));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Arch Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new DrawArc();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 450));
        frame.setVisible(true);
    }
}

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

Draw Arch Demo

How do I draw an ellipse in Java 2D?

The Ellipse2D class define an ellipse that is defined by a framing rectangle. You can create an ellipse using a double or float values. When creating an ellipse using double values use the Ellipse2D.Double class. And for the float values you can use the Ellipse2D.Float class.

package org.kodejava.example.awt.geom;

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

public class DrawEllipse extends JApplet {
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        
        g2.setPaint(Color.RED);
        g2.setStroke(new BasicStroke(5.0f));
        g2.draw(new Ellipse2D.Double(50, 50, 250, 250));

        g2.setPaint(Color.BLUE);
        g2.fill(new Ellipse2D.Double(10, 10, 40, 40));

        g2.setPaint(Color.YELLOW);
        g2.fill(new Ellipse2D.Double(10, 300, 40, 40));

        g2.setPaint(Color.GREEN);
        g2.fill(new Ellipse2D.Double(300, 300, 40, 40));

        g2.setPaint(Color.ORANGE);
        g2.fill(new Ellipse2D.Double(300, 10, 40, 40));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Ellipse Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JApplet applet = new DrawEllipse();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setSize(new Dimension(400, 400));
        frame.setVisible(true);
    }
}

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

Draw Ellipse Demo