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 disable keyboard events in JTextArea?

The following example demonstrate how to disable some keys in JTextArea and JScrollPane using the InputMap. In the disableKeys() method below we disable the arrow keys including the UP, DOWN, LEFT and RIGHT.

Let’s see the code snippet below:

package org.kodejava.example.swing;

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

public class DisableKeyDemo extends JFrame {
    public DisableKeyDemo() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("Disable Keys Demo");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JTextArea textArea = new JTextArea("Hello World!");
        JScrollPane scrollPane = new JScrollPane(textArea);
        disableKeys(textArea.getInputMap());
        disableKeys(scrollPane.getInputMap(
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));

        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void disableKeys(InputMap inputMap) {
        String[] keys = {"UP", "DOWN", "LEFT", "RIGHT"};
        for (String key : keys) {
            inputMap.put(KeyStroke.getKeyStroke(key), "none");
        }
    }

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

How do I create a single line JTextArea?

The following example will show you how to create a single line JTextArea. A single line means that you cannot insert a new line in the text area. When pressing the enter key it will be replaced by a space.

This can be done by putting a property called filterNewlines and set its value to Boolean.TRUE into the document model of the JTextArea.

package org.kodejava.example.swing;

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

public class SingleLineTextArea extends JFrame {
    private SingleLineTextArea() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("Single Line Text Area");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);

        // Filter a new line, pressing enter key will be replaced
        // with a space instead.
        textArea.getDocument().putProperty("filterNewlines",
                Boolean.TRUE);

        JScrollPane scrollPane = new JScrollPane(textArea);

        // Pressing the Save button print out the text area text
        // into the console.
        JButton button = new JButton("Save");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(textArea.getText());
            }
        });
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }

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

Single Line TextArea

How do I move focus from JTextArea using TAB key?

The default behavior when pressing the tabular key in a JTextArea is to insert a tab spaces in the text area. In this example you’ll see how to change this to make the tab key to transfer focus to other component forward or backward.

The main routine can be found in the key listener section. When the tab key is pressed we will tell the text area to transfer to focus into other component. Let’s see the code snippet below.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TextAreaTabMoveFocus extends JFrame {
    public TextAreaTabMoveFocus() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("JTextArea TAB DEMO");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JTextField textField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        final JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);

        // Add key listener to change the TAB behavior in
        // JTextArea to transfer focus to other component forward
        // or backward.
        textArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_TAB) {
                    if (e.getModifiers() > 0) {
                        textArea.transferFocusBackward();
                    } else {
                        textArea.transferFocus();
                    }
                    e.consume();
                }
            }
        });

        getContentPane().add(textField, BorderLayout.NORTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(passwordField, BorderLayout.SOUTH);
    }

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

How do I read text file into JTextArea?

Using the read(Reader in, Object desc) method inherited from the JTextComponent allow us to populate a JTextArea with text content from a file. This example will show you how to do it.

In this example we use an InputStreamReader to read a file from our application resource. You could use other Reader implementation such as the FileReader to read to content of a file. Let’s see the code below.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStreamReader;

public class PopulateTextAreaFromFile extends JFrame {
    public PopulateTextAreaFromFile() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("Populate JTextArea from File");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        try {
            //
            // Read some text from the resource file to display in
            // the JTextArea.
            //
            textArea.read(new InputStreamReader(
                    getClass().getResourceAsStream("/data.txt")),
                    null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

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

How do I select all text in JTextArea?

Selecting all text in the JTextArea component can be done by using the selectAll() method. In the example below we use a button action to do the selection. After select the text we transfer focus back to the JTextArea so that the highlighted text is shown.

package org.kodejava.example.swing;

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

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

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

        final JTextArea textArea = new JTextArea(
                "The quick brown fox jumps over the lazy dog.");
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(400, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        final JButton button1 = new JButton("Select All");
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textArea.selectAll();

                // Transfer focus to JTextArea to show the selected
                // text.
                button1.transferFocusBackward();
            }
        });
        final JButton button2 = new JButton("Get Selected Text");
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String text = textArea.getSelectedText();
                System.out.println("Text = " + text);
            }
        });

        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(button1);
        buttonPanel.add(button2);

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

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

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TextAreaSelectAll.showFrame();
            }
        });
    }
}

And here the screenshoot of the code snippet above:

JTextArea Select All Text

How do I append text to JTextArea?

To append text to the end of the JTextArea document we can use the append(String str) method. This method does nothing if the document is null or the string is null or empty.

package org.kodejava.example.swing;

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

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

    private void initializeUI() {
        String text = "The quick brown fox ";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        String appendText = "jumps over the lazy dog.";
        textArea.append(appendText);

        this.setPreferredSize(new Dimension(400, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }

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

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TextAreaAppendText.showFrame();
            }
        });
    }
}

How do I insert a text in a specified position in JTextArea?

The insert(String str, int pos) of the JTextArea allows us to insert a text at the specified position. In the example below we insert brown and over words into the current JTextArea text.

package org.kodejava.example.swing;

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

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

    private void initializeUI() {
        String text = "The quick fox jumps the lazy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.insert("brown ", 10);
        textArea.insert("over ", 26);

        this.setPreferredSize(new Dimension(300, 100));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }

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

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

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TextAreaInsertText.showFrame();
            }
        });
    }
}