Programming Code Examples

How to Work with Swing Operations in Java18 min read

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:

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.

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.

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:

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:

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:

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:

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.

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:

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:

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:

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.

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.

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.

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:

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:

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:

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.

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.

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:

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:

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:

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.

Add comment