In this article we will look at some of the swing controls available in javax.swing package along with sample Java code for each control.
Swing is a collection of libraries for creating graphical user interfaces (GUIs) in Java. It is built on top of the AWT (Abstract Window Toolkit) and provides a more flexible and powerful set of widgets for creating Java GUI applications.
Here is an example of a basic Swing program that creates a simple window with a button:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import javax.swing.*; import java.awt.*; public class SwingExample { public static void main(String[] args) { // Create a new JFrame container JFrame frame = new JFrame("Swing Example"); // Set the frame to exit the program when closed frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a new button and add it to the frame JButton button = new JButton("Click me!"); frame.add(button, BorderLayout.CENTER); // Pack the frame and make it visible frame.pack(); frame.setVisible(true); } } |

This creates a new window with a button labeled “Click me!” in the center. When the button is clicked, the program does not respond because the button is not listening for any action. To make it respond, you should create a listener for the button and make it do something.
1 2 3 4 5 6 7 8 | button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ //Do something when button is clicked JOptionPane.showMessageDialog(frame, "Button Clicked!"); } }); |
Swing components can be added to the frame layout manager of your choice and you can also customize the look and feel by modifying the UIManager class.
Here’s a list of some commonly used Swing controls and a brief explanation of what they are used for, along with example code for each:
JButton: A button control that can be clicked by the user to perform an action.
1 2 3 4 | JButton button = new JButton("Click me!"); frame.add(button); |
Swing JLabel Control
A JLabel is a Swing control that displays a text or an image. It is typically used to label or describe other components, like a text field or a button.
Here is an example of how to create a JLabel and add it to a JFrame:
1 2 3 4 5 6 7 8 9 10 | JFrame frame = new JFrame("Code4Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("This is a label."); frame.add(label, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); |
In this example, the JLabel is created with the text “This is a label.” and added to the center of the frame using a BorderLayout manager.
You can also create a JLabel with an image:
1 2 3 4 5 | ImageIcon icon = new ImageIcon("image.png"); JLabel label = new JLabel(icon); frame.add(label, BorderLayout.CENTER); |
You can customize the text and the icon of the label at runtime by calling the setText() and setIcon() methods respectively.
Also, JLabel have some other useful methods like setFont(), setHorizontalAlignment(), setVerticalAlignment() and many others.
It’s worth noting that a JLabel does not generate any event, and therefore it is not interactive, so it can’t be selected, focused, or activated. It’s just used as a visual representation, either a text or an image.
A JLabel is a non-interactive Swing control that is used to display text and/or images. It has a variety of properties and methods that can be used to customize its appearance and behavior. Here are some commonly used properties and methods of JLabel:
setText(String text)
: Sets the text that the label displays.setIcon(Icon icon)
: Sets the icon that the label displays.setHorizontalAlignment(int alignment)
: Sets the horizontal alignment of the text or icon within the label. The alignment can be one of the following constants: LEFT, CENTER, RIGHT, LEADING, or TRAILING.setVerticalAlignment(int alignment)
: Sets the vertical alignment of the text or icon within the label. The alignment can be one of the following constants: TOP, CENTER, or BOTTOM.setFont(Font font)
: Sets the font used to render the text.setForeground(Color color)
: Sets the color used to render the text.setOpaque(boolean opaque)
: Specifies whether the label’s background should be painted.setToolTipText(String text)
: Sets the text that is displayed as a tooltip when the mouse hovers over the label.getText()
: Returns the text displayed by the label.getIcon()
: Returns the icon displayed by the label.
Here is an example of using some of these methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | JFrame frame = new JFrame("Label Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("This is a label."); label.setFont(new Font("Arial", Font.BOLD, 14)); label.setForeground(Color.BLUE); label.setHorizontalAlignment(SwingConstants.CENTER); label.setVerticalAlignment(SwingConstants.TOP); label.setToolTipText("This is a tooltip text."); frame.add(label, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); |
In this example, a JLabel is created with the text “This is a label.” and added to the center of the frame using a BorderLayout manager. Then, the font, foreground color, horizontal alignment, vertical alignment and tooltip text of the label are set using the appropriate methods.
It’s important to note that JLabel can also display both text and an icon by using setIcon(Icon icon) and setText(String text) methods together. The icon and text will be displayed side by side, with the icon on the left if the text is set first, or on the right if the icon is set first.
Also, keep in mind that some of these properties have constants to set them, like horizontal and vertical alignment, that you can use instead of hard-coded values.
Swing JTextField Control
A JTextField is a Swing control that allows the user to enter a single line of text. It is often used in forms, dialogs, and other user interface components where the user needs to enter a small amount of text.
Here’s an example of how to create a JTextField and add it to a JFrame:
1 2 3 4 5 6 7 8 9 10 | JFrame frame = new JFrame("Text Field Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField textField = new JTextField(20); frame.add(textField, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); |
In this example, a JTextField is created with a width of 20 characters and added to the top of the frame using a BorderLayout manager.
You can also customize the text of the text field at runtime by calling the setText(String text)
and getText()
methods.
1 2 3 4 | textField.setText("initial text"); String enteredText = textField.getText(); |
It’s important to note that JTextField does not include a built-in label that indicates the purpose of the text field, you should use a JLabel to describe it.
Also, you can set an action listener on JTextField to execute a certain action when the user press ‘Enter’ key by calling the addActionListener() method, like this:
1 2 3 4 5 6 7 8 | textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = textField.getText(); // Do something with the text } }); |
Additionally, you can control the format and type of input of JTextField by using DocumentFilter, which you can set it by calling the setDocument() method. And you can set a limit of characters the user can enter.
In summary, JTextField is a simple but powerful control that can be easily integrated into any Java Swing application to provide text input functionality to the user.
A JTextField is a Swing control that allows the user to enter a single line of text. It has a variety of properties and methods that can be used to customize its appearance and behavior. Here are some commonly used properties and methods of JTextField:
setText(String text)
: Sets the text displayed in the text field.getText()
: Returns the text currently displayed in the text field.setColumns(int columns)
: Sets the number of columns (or the width) of the text field.setEditable(boolean editable)
: Sets whether the text field can be edited by the user or not.setFont(Font font)
: Sets the font used to render the text.setForeground(Color color)
: Sets the color used to render the text.setBackground(Color color)
: Sets the background color of the text field.setSelectionStart(int start)
: Sets the starting point of the text selection.setSelectionEnd(int end)
: Sets the ending point of the text selection.setSelectionColor(Color color)
: Sets the color used to highlight the selected text.addActionListener(ActionListener listener)
: Registers an action listener to be notified when the user press ‘Enter’ key on the text field.setDocument(Document doc)
: Associates the text field with a specific document model.
Here is an example of how to use some of these properties:
1 2 3 4 5 6 | JTextField textField = new JTextField("Initial text", 20); textField.setEditable(false); textField.setBackground(Color.LIGHT_GRAY); textField.setSelectionColor(Color.YELLOW); |
In this example, a JTextField is created with an initial text “Initial text” and width of 20 columns, then it’s set as non-editable and also the background color and selection color are set to certain colors.
It’s worth mentioning that you can also use JTextField with DocumentFilter to control input format, limit the number of characters user can enter and also you can use a plain document, or you can create your custom document model by subclassing AbstractDocument class.
Also, you can use the addActionListener method to listen to ‘Enter’ key events on JTextField, so you can perform an action when the user press ‘Enter’ key.
In summary, JTextField is a versatile control that can be used to provide text input functionality to the user in a Swing application, and its properties and methods can be easily customized to meet the specific needs of the application.
Swing JToggleButton Control
A JToggleButton is a type of button in Java Swing that has two states: selected and unselected. It is similar to a checkbox or a radio button, but has a different appearance and can be used alone or in groups.
Here’s an example of how to create a JToggleButton and add it to a JFrame:
1 2 3 4 5 6 7 8 9 10 | JFrame frame = new JFrame("Toggle Button Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JToggleButton toggleButton = new JToggleButton("Click me!"); frame.add(toggleButton, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); |
In this example, a JToggleButton is created with the label “Click me!” and added to the top of the frame using a BorderLayout manager. When the button is clicked, it will toggle its state between selected and unselected.
You can also customize the text of the toggle button at runtime by calling the setText() method and you can get the current state of the toggle button by calling the isSelected()
method.
1 2 3 4 | toggleButton.setText("New Text"); boolean state = toggleButton.isSelected(); |
It’s important to notice that like JRadioButton, JToggleButton can be grouped together by using a ButtonGroup to make sure that only one of the buttons in the group can be selected at a time.
1 2 3 4 5 6 7 | ButtonGroup group = new ButtonGroup(); JToggleButton button1 = new JToggleButton("Option 1"); JToggleButton button2 = new JToggleButton("Option 2"); group.add(button1); group.add(button2); |
Also, it is recommended to use an ItemListener or an ActionListener to listen for toggle button events, you can add them to the JToggleButton instance by calling the addItemListener()
or addActionListener()
method respectively.
1 2 3 4 5 6 7 8 9 | toggleButton.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { boolean selected = e.getStateChange() == ItemEvent.SELECTED; // Do something when the button is toggled } }); |
in the ItemListener example provided above, when the toggle button’s state changes, the itemStateChanged
method will be called and the current state of the toggle button can be obtained by calling e.getStateChange()
. The returned value is one of the constants in ItemEvent
class: SELECTED
or DESELECTED
. The implementation can then take appropriate action depending on whether the toggle button is selected or not.
Similarly, you can use an ActionListener to listen for toggle button events. Here’s an example of how to use an ActionListener:
1 2 3 4 5 6 7 8 | toggleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean selected = toggleButton.isSelected(); // Do something when the button is clicked } }); |
In this example, the actionPerformed
method will be called when the toggle button is clicked, and the current state of the toggle button can be obtained by calling the isSelected()
method on the toggle button instance.
It’s also worth noting that JToggleButton has a couple of constructors that allows you to set the initial state of the button, like this:
1 2 3 | JToggleButton toggleButton = new JToggleButton("Click me!", true); |
The above example creates a toggle button with the label “Click me!” and the initial state set to true (selected).
In summary, JToggleButton is a versatile control that can be used to provide toggle functionality to the user in a Swing application, and its properties and methods can be easily customized to meet the specific needs of the application.
Swing JTextArea Control
A JTextArea is a Swing control that allows the user to enter or view multiple lines of text. It is similar to a text field, but it is designed to handle larger amounts of text and to provide more formatting options.
Here’s an example of how to create a JTextArea and add it to a JFrame:
1 2 3 4 5 6 7 8 9 10 11 12 | JFrame frame = new JFrame("Text Area Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea textArea = new JTextArea(5, 20); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); frame.add(new JScrollPane(textArea), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); |
In this example, a JTextArea is created with 5 rows and 20 columns and it’s added to the frame using a JScrollPane, which will allow the user to scroll through the text area if the text becomes too large to fit. Additionally, setLineWrap(true)
and setWrapStyleWord(true)
properties are used to set the wrapping style to wrap the lines at word boundaries so that text doesn’t disappear off the right edge of the text area.
You can customize the text of the text area at runtime by calling the setText(String text)
and getText()
methods.
1 2 3 4 | textArea.setText("Initial text"); String enteredText = textArea.getText(); |
It’s important to notice that JTextArea doesn’t include a built-in scroll bar, you should use a JScrollPane to provide the scrolling functionality.
Also, it is recommended to use a DocumentListener to listen for document events like changing the text inside the JTextArea, you can add it by calling the getDocument().addDocumentListener(listener)
method on the JTextArea instance.
1 2 3 4 5 6 7 | textArea.getDocument().addDocumentListener(new DocumentListener(){ public void changedUpdate(DocumentEvent e){ // Do something when the text area changes } }); |
In summary, JTextArea is a powerful control that can be used to provide a multi-line text input or output functionality to the user in a Swing application. It allows the user to enter or view large amounts of text and provides more formatting options than a simple text field. JTextArea can be used in different ways like displaying large amount of text or as a log or even as a text editor. Additionally, JTextArea can be customized through its properties and methods, and events can be listened to detect changes to the text.
JTextArea is a Swing control that allows the user to enter or view multiple lines of text. It has a variety of properties and methods that can be used to customize its appearance and behavior. Here are some commonly used properties and methods of JTextArea:
setText(String text)
: Sets the text displayed in the text area.getText()
: Returns the text currently displayed in the text area.setRows(int rows)
: Sets the number of rows of the text area.setColumns(int columns)
: Sets the number of columns (or the width) of the text area.setEditable(boolean editable)
: Sets whether the text area can be edited by the user or not.setLineWrap(boolean wrap)
: Sets whether the text should be wrapped at the end of the line or not.setWrapStyleWord(boolean wrap)
: If true, words are wrapped by word boundaries; otherwise, lines are wrapped by character boundaries.setFont(Font font)
: Sets the font used to render the text.setForeground(Color color)
: Sets the color used to render the text.setBackground(Color color)
: Sets the background color of the text area.setSelectionStart(int start)
: Sets the starting point of the text selection.setSelectionEnd(int end)
: Sets the ending point of the text selection.setSelectionColor(Color color)
: Sets the color used to highlight selected text.getSelectionStart()
: Returns the starting point of the text selection.getSelectionEnd()
: Returns the ending point of the text selection.replaceSelection(String content)
: Replaces the selected text with the specified content.getDocument()
: Returns the document object associated with the text area, which can be used to add document listeners and to perform other advanced operations on the text.
Additionally, JTextArea implements the Scrollable interface which allows the programmer to specify which scrollbars it should display, however this is typically done by adding the JTextArea to a JScrollPane.
setCaretPosition(int position)
sets the position of the caret, the blinking vertical line where new characters will be inserted.
getCaretPosition()
gets the current position of the caret.
append(String str)
Appends the given text to the end of the document.
setTabSize(int size)
Changes the number of characters that a tab takes up.
JTextArea also generates a variety of events, like CaretEvent
, DocumentEvent
and UndoableEditEvent
. These events allow the developer to listen to modifications or actions made in the JTextArea and handle them.
Here are a couple of examples that demonstrate different ways to use JTextArea:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | JFrame frame = new JFrame("Text Area Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea textArea = new JTextArea(5, 20); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setText("Initial text"); frame.add(new JScrollPane(textArea), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); |
This example creates a JTextArea with 5 rows and 20 columns and adds it to a JFrame with a scroll bar to the user can scroll the text if needed. Also, the text “Initial text” is set as the initial text displayed in the JTextArea.
Example:
1 2 3 4 5 6 7 8 9 10 | JTextArea textArea = new JTextArea(5, 20); textArea.setEditable(false); textArea.getDocument().addDocumentListener(new DocumentListener(){ public void changedUpdate(DocumentEvent e){ // Do something when the text area changes } }); |
This example creates a JTextArea with 5 rows and 20 columns, sets it to be non-editable so the user can’t edit the text area and adds a DocumentListener to the JTextArea so you can track the changes of the text in the JTextArea and make some action based on that.
Note that both examples add the JTextArea to a JFrame with JScrollPane, this is a best practice as JTextArea doesn’t include a built-in scroll bar, JScrollPane provides the scrolling functionality.
You can also set a different font, add a tooltip, set the background color and so on, you can play around with its properties and events to make it more interactive and useful.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | JFrame frame = new JFrame("Text Editor Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea textArea = new JTextArea(5, 20); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); frame.add(new JScrollPane(textArea), BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); fileMenu.add(openItem); fileMenu.add(saveItem); menuBar.add(fileMenu); frame.setJMenuBar(menuBar); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { textArea.setText(new String(Files.readAllBytes(file.toPath()))); } catch (IOException ex) { ex.printStackTrace(); } } } }); saveItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { Files.write(file.toPath(), textArea.getText().getBytes()); } catch (IOException ex) { ex.printStackTrace(); } } } }); frame.pack(); frame.setVisible(true); |
This example extends the previous examples by adding a JMenuBar and two JMenuItems to the JFrame, “Open” and “Save” which allows the user to open a file and display its contents in the JTextArea, or to save the contents of the JTextArea to a file. To accomplish this, it uses a JFileChooser to let the user select a file to open or save, and the Java NIO Files
class to read or write the contents of the file.
You can see how the code sets the properties of the JTextArea and uses the setText()
and getText()
methods to manipulate the text. It also uses a JMenuBar, JMenu and JMenuItem to create a menu with options to open and save files, and it also uses JFileChooser to allow the user to select the file to open or save. The JFileChooser will open a dialog box that allows the user to navigate through their file system and select a file to open or specify the name and location of a file to save. The showOpenDialog()
and showSaveDialog()
methods of JFileChooser are used to display the open or save dialog respectively.
Once the user has selected a file, the getSelectedFile()
method is used to retrieve the file that the user has selected. Then, the code uses the Files.readAllBytes(file.toPath())
method to read the contents of the file and set it as the text in the JTextArea, In the case of save method, It will use Files.write(file.toPath(), textArea.getText().getBytes())
method to save the contents of the JTextArea to the file selected.
It’s a simple example of JTextArea, it will help you to understand the basic functionality of JTextArea and how you can use it in a more complex application. You can add more functionality or enhancements like adding keyboard shortcuts, adding a toolbar and so on.
JCheckBox: A control that allows the user to select multiple options from a group of options.
JRadioButton: A control that allows the user to select one option from a group of options.
JComboBox: A control that allows the user to select one option from a drop-down list.
It’s important to notice that this is just a small set of examples and the Swing package has many more options and functionalities, like JList, JTable, JTabbedPane, JTree, JProgressBar, JSlider and many others.