Swing
Swing
#swing
Table of Contents
About 1
Remarks 2
Examples 2
Chapter 2: Basics 6
Examples 6
Listening to an Event 10
Chapter 3: Graphics 13
Examples 13
Intro 13
class Board 13
Colors 14
Drawing images 14
loading an image 14
Syntax 17
Examples 17
Example 19
Chapter 5: GridLayout 21
Examples 21
Chapter 6: JList 24
Examples 24
Examples 25
Border layout 25
Flow layout 26
Grid layout 27
Chapter 8: MigLayout 29
Examples 29
Wrapping elements 29
Examples 30
Syntax 34
Examples 34
Creating a DefaultStyledDocument 34
Copying DefaultStyledDocument 34
Syntax 36
Examples 36
Examples 39
Timer In JFrame 39
Examples 40
Remarks 43
Examples 43
Example 44
Adding Components 45
Creating a Component 45
Example 46
Common Components 48
It is an unofficial and free swing ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official swing.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with swing
Remarks
Swing has been superseded by JavaFX. Oracle generally recommends developing new
applications with JavaFX. Still: Swing will be supported in Java for the foreseeable future. JavaFX
also integrates well with Swing, to allow transitioning applications smoothly.
It is strongly recommended to have most of your Swing components on the Event Dispatch
Thread. It's easy to forget to bundle your GUI setup into a invokeLater call. From the Java
Documentation:
Swing event handling code runs on a special thread known as the event dispatch
thread. Most code that invokes Swing methods also runs on this thread. This is
necessary because most Swing object methods are not "thread safe": invoking them
from multiple threads risks thread interference or memory consistency errors. Some
Swing component methods are labelled "thread safe" in the API specification; these
can be safely invoked from any thread. All other Swing component methods must be
invoked from the event dispatch thread. Programs that ignore this rule may function
correctly most of the time, but are subject to unpredictable errors that are difficult to
reproduce.
Also, unless for good reason, always make sure that you called
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) or else you might possibly have to deal
with a memory leak if you forget to destroy the JVM.
Examples
Incrementing with a button
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
/**
* A very simple Swing example.
*/
public class SwingExample {
/**
* The number of times the user has clicked the button.
*/
private long clickCount;
/**
* The main method: starting point of this application.
*
https://riptutorial.com/ 2
* @param arguments the unused command-line arguments.
*/
public static void main(final String[] arguments) {
new SwingExample().run();
}
/**
* Schedule a job for the event-dispatching thread: create and show this
* application's GUI.
*/
private void run() {
SwingUtilities.invokeLater(this::createAndShowGui);
}
/**
* Create the simple GUI for this application and make it visible.
*/
private void createAndShowGui() {
// Create the frame and make sure the application exits when the user closes
// the frame.
JFrame mainFrame = new JFrame("Counter");
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Result
As the button labeled "Click me!" is pressed the click count will increase by one:
https://riptutorial.com/ 3
"Hello World!" on window title with lambda
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
Using java.lang.Runnable we make our "Hello World!" example available to Java users with
https://riptutorial.com/ 4
versions dating all the way back to the 1.2 release:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
@Override
public void run(){
JFrame frame = new JFrame("Hello World!");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
}
});
}
}
https://riptutorial.com/ 5
Chapter 2: Basics
Examples
Delay a UI task for a specific period
All Swing-related operations happen on a dedicated thread (the EDT - Event Dispatch Thread). If
this thread gets blocked, the UI becomes non-responsive.
Therefore, if you want to delay an operation you cannot use Thread.sleep. Use a javax.swing.Timer
instead. For example the following Timer will reverse the text of on a JLabel
A complete runnable example which uses this Timer is given below: the UI contains a button and a
label. Pressing the button will reverse the text of the label after a 2 second delay
import javax.swing.*;
import java.awt.*;
https://riptutorial.com/ 6
frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
frame.setVisible( true );
}
}
Updating the state of a Swing component must happen on the Event Dispatch Thread (the EDT).
The javax.swing.Timer triggers its ActionListener on the EDT, making it a good choice to perform
Swing operations.
The following example updates the text of a JLabel each two seconds:
A complete runnable example which uses this Timer is given below: the UI contains a label, and
the text of the label will be reverted each two seconds.
import javax.swing.*;
import java.awt.*;
In the ActionListener attached to a javax.swing.Timer, you can keep track of the number of times
the Timer executed the ActionListener. Once the required number of times is reached, you can use
https://riptutorial.com/ 7
the Timer#stop() method to stop the Timer.
A complete runnable example which uses this Timer is given below: it shows a UI where the text of
the label will count from zero to five. Once five is reached, the Timer is stopped.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
https://riptutorial.com/ 8
public class FrameCreator {
frame.setVisible(true);
});
}
As you may notice if you run this code, the label is position in a very bad place. This is difficult to
change in a good manner using the add method. To allow more dynamic and flexible placing check
out Swing Layout Managers.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
https://riptutorial.com/ 9
//Calling SwingUtilities.invokeLater makes sure that happens.
SwingUtilities.invokeLater(() -> {
CustomFrame frame = new CustomFrame("Hello Jungle");
//This is simply being done so it can be accessed later
statFrame = frame;
frame.setVisible(true);
});
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
//Handle error
}
Listening to an Event
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
//Add a button
JButton btn = new JButton("Hello button");
//And a textbox
JTextField field = new JTextField("Name");
field.setSize(150, 50);
//This next block of code executes whenever the button is clicked.
btn.addActionListener((evt) -> {
JLabel helloLbl = new JLabel("Hello " + field.getText());
add(helloLbl);
validate();
});
add(btn);
add(field);
}
https://riptutorial.com/ 10
//All Swing actions should be run on the Event Dispatch Thread (EDT)
//Calling SwingUtilities.invokeLater makes sure that happens.
SwingUtilities.invokeLater(() -> {
CustomFrame frame = new CustomFrame("Hello Jungle");
//This is simply being done so it can be accessed later
frame.setVisible(true);
});
}
This code can be added to any event like a listener, button, etc. A blocking JDialog will appear and
will remain until the process is complete.
Assuming that you have successfully created a JFrame and that Swing has been imported...
import javax.Swing.*;
or You can import the Swing Components/Frame that you intend to use
import javax.Swing.Jframe;
https://riptutorial.com/ 11
import javax.Swing.JButton;
});
B.setBounds(0, 0,frame.getHeight(), frame.getWidth());
B.setVisible(true);
frame.add(B);
////////////////////////////////////////////////////////////////////////////
}
When the button is clicked... "Hello World" should also appear in your console.
https://riptutorial.com/ 12
Chapter 3: Graphics
Examples
Using the Graphics class
Intro
The Graphics class allows you to draw onto java components such as a Jpanel, it can be used to
draw strings, lines, shapes and images. This is done by overriding the paintComponent(Graphics g)
method of the JComponent you are drawing on using the Graphics object received as argument to do
the drawing:
class Board
import java.awt.*;
import javax.swing.*;
public Board() {
setBackground(Color.WHITE);
}
@override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
import javax.swing.*;
public DrawingCanvas() {
https://riptutorial.com/ 13
pack(); // sets JFrame dimension to contain subcomponents
setResizable(false);
setTitle("Graphics Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Colors
To draw shapes with different colors you must set the color of the Graphics object before each
draw call using setColor:
Drawing images
Images can be drawn onto a JComponent using the drawImage method of class Graphics:
loading an image
BufferedImage img;
try {
img = ImageIO.read(new File("stackoverflow.jpg"));
} catch (IOException e) {
throw new RuntimeException("Could not load image", e);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
https://riptutorial.com/ 14
int y = 0;
g.drawImage(img, x, y, this);
}
The MyFrame class the extends JFrame and also contains the main method
import javax.swing.JFrame;
The MyPanel class that extends JPanel and has the paintComponent method
https://riptutorial.com/ 15
import java.awt.Graphics;
import javax.swing.JPanel;
https://riptutorial.com/ 16
Chapter 4: GridBag Layout
Syntax
• frame.setLayout(new GridBagLayout()); //Set GridBagLayout for frame
• pane.setLayout(new GridBagLayout()); //Set GridBagLayout for Panel
• JPanel pane = new JPanel(new GridBagLayout()); //Set GridBagLayout for Panel
• GridBagConstraints c = new GridBagConstraints() //Initialize a GridBagConstraint
Examples
How does GridBagLayout work?
Layouts are used whenever you want your components to not just be displayed next to each other.
The GridBagLayout is a useful one, as it divides your window into rows and columns, and you
decide which row and column to put components into, as well as how many rows and colums big
the component is.
Let's take this window as an example. Grid lines have been marked on to show the layout.
https://riptutorial.com/ 17
Component Position Size
JSlider 0, 2 3, 1
JScrollBar 0, 3 3, 1
Note that position 0, 0 is at the top left: x (column) values increase from left to right, y (row) values
increase from top to bottom.
To start laying out components in a GridBagLayout, first set the layout of your JFrame or content
pane.
frame.setLayout(new GridBagLayout());
//OR
pane.setLayout(new GridBagLayout());
//OR
JPanel pane = new JPanel(new GridBagLayout()); //Add the layout when creating your content
pane
Note that you never define the size of the grid. This is done automatically as you add your
components.
To make sure that your components fill up the size of the window, you may want to set the weight
of all componets to 1. Weight is used to determine how to distribute space among columns and
rows.
c.weightx = 1;
c.weighty = 1;
Another thing that you may want to do is make sure that components take up as much horizontal
space as they can.
c.fill = GridBagConstraints.HORIZONTAL;
When creating components, you will want to set where on the grid it should go, and how many grid
tiles it should use. For example, to place a button in the 3rd row in the 2nd column, and take up a
https://riptutorial.com/ 18
5 x 5 grid space, do the following. Keep in mind that the grid starts at 0, 0, not 1, 1.
When adding components to your window, remember to pass the constraints as a parameter. This
can be seen in the last line in the code example above.
You can reuse the same GridBagConstraints for every component - changing it after adding a
component doesn't change the previously added component.
Example
Here's the code for the example at the start of this section.
JFrame frame = new JFrame("Super Awesome Window Title!"); //Create the JFrame and give it a
title
frame.setSize(512, 256); //512 x 256px size
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Quit the application when the
JFrame is closed
JPanel pane = new JPanel(new GridBagLayout()); //Create a pane to house all content, and give
it a GridBagLayout
frame.setContentPane(pane);
https://riptutorial.com/ 19
pane.add(buttonC, c);
https://riptutorial.com/ 20
Chapter 5: GridLayout
Examples
How GridLayout works
A GridLayout is a layout manager which places components inside a grid with equal cell sizes. You
can set the number of rows, columns, the horizontal gap and the vertical gap using the following
methods:
• setRows(int rows)
• setColumns(int columns)
• setHgap(int hgap)
• setVgap(int vgap)
If the number of rows or columns is unknown, you can set the respective variable to 0. For
example:
new GridLayout(0, 3)
This will cause the GridLayout to have 3 columns and as many rows as needed.
The following example demonstrates how a GridLayout lays out components with different values
for rows, columns, horizontal gap, vertical gap and screen size.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
https://riptutorial.com/ 21
public void createAndShowGUI() {
gridLayout = new GridLayout(5, 5, 3, 3);
fillGrid();
https://riptutorial.com/ 22
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
https://riptutorial.com/ 23
Chapter 6: JList
Examples
Modify the selected elements in a JList
the selected items in the list can be modified through the ListSelectionModel of the JList:
ListSelectionModel sm = myList.getSelectionModel();
sm.clearSelection(); // clears the selection
sm.setSelectionInterval(index, index); // Sets a selection interval
// (single element, in this case)
Alternatively, JList also provides some convenient methods to directly manipulate the selected
indexes:
https://riptutorial.com/ 24
Chapter 7: Layout management
Examples
Border layout
Border layout is one of the simplest layout managers. The way to use a layout manager is to set
the manager of a JPanel.
In BorderLayout slots can also be empty. The layout manager will automatically compensate for any
empty spaces, resizing when needed.
https://riptutorial.com/ 25
Flow layout
import javax.swing.*;
import java.awt.FlowLayout;
@Override
public void run(){
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JButton("One"));
panel.add(new JButton("Two"));
panel.add(new JButton("Three"));
panel.add(new JButton("Four"));
panel.add(new JButton("Five"));
Flow layout is the simplest layout manager that Swing has to offer. Flow layout tries to put
everything on one line, and if the layout overflows the width, it will wrap the line. The order is
specified by the order you add components to your panel.
Screenshots:
https://riptutorial.com/ 26
Grid layout
You pass the number of rows and columns you want the grid to have to the GridLayout's
constructor, for example new GridLayout(3, 2) will create a GridLayout with 3 rows and 2 columns.
When adding components to a container with the GridLayout, the components will be added row by
row, from left to right:
import javax.swing.*;
import java.awt.GridLayout;
jFrame.setContentPane(jPanel);
jFrame.pack();
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
}
}
https://riptutorial.com/ 27
A more detailed description is available: GridLayout
https://riptutorial.com/ 28
Chapter 8: MigLayout
Examples
Wrapping elements
This example demonstrates how to place 3 buttons in total with 2 buttons being in the first row.
Then a wrap occurs, so the last button is in a new row.
The constraints are simple strings, in this case "wrap" while placing the component.
panel.add(button1);
// Notice the wrapping
panel.add(button2, "wrap");
panel.add(button3);
demo.add(panel);
demo.setVisible(true);
}
}
Output:
https://riptutorial.com/ 29
Chapter 9: MVP Pattern
Examples
Simple MVP Example
To illustrate a simple example usage of the MVP pattern, consider the following code which
creates a simple UI with only a button and a label. When the button is clicked, the label updates
with the number of times the button has been clicked.
We have 5 classes:
/**
* A minimal class to maintain some state
*/
public class Model {
private int count = 0;
/**
* Provides methods to notify on user interaction
*/
public interface ViewListener {
public void onButtonClicked();
}
The view class constructs all UI elements. The view, and only the view, should have reference to
UI elements (ie. no buttons, text fields, etc. in the presenter or other classes).
/**
* Provides the UI elements
*/
https://riptutorial.com/ 30
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public View() {
final JFrame frame = new JFrame();
frame.setSize(200, 100);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout());
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
notifyListenersOnButtonClicked();
}
});
frame.add(button);
frame.setVisible(true);
}
// Subscribe a listener
public void addListener(final ViewListener listener) {
listeners.add(listener);
}
...
https://riptutorial.com/ 31
final Button button = new Button("Hello, world!");
// In order to do so, our interface must be changed to accept the event parametre
button.addActionListener((event) -> {
notifyListeners(ViewListener::onButtonClicked, event);
// Example of calling methodThatTakesALong, would be the same as callying:
// notifyListeners((listener, long)->listener.methodThatTakesALong(long), 10L)
notifyListeners(ViewListener::methodThatTakesALong, 10L);
});
frame.add(button);
...
/**
* Iterates through the subscribed listeneres notifying each listener individually.
* Note: the {@literal '<T>' in private <T> void} is a Bounded Type Parametre.
*
* @param <T> Any Reference Type (basically a class).
*
* @param consumer A method with two parameters and no return,
* the 1st parametre is a ViewListner,
* the 2nd parametre is value of type T.
*
* @param data The value used as parametre for the second argument of the
* method described by the parametre consumer.
*/
private <T> void notifyListeners(final BiConsumer<ViewListener, T> consumer, final T data) {
// Iterate through the list, notifying each listener, java8 style
listeners.forEach((listener) -> {
});
}
Here only one notify-method is needed, the actual listener method and its parameter are passed
on as parameters. In case needed this can also be used for something a little less nifty than actual
event handling, it all works as long as there is a method in the interface, e.g.:
notifyListeners(ViewListener::methodThatTakesALong, -1L);
The presenter can take in the view and add itself as a listener. When the button is clicked in the
view, the view notifies all listeners (including the presenter). Now that the presenter is notified, it
https://riptutorial.com/ 32
can take appropriate action to update the model (ie. the state of the application), and then update
the view accordingly.
/**
* Responsible to responding to user interaction and updating the view
*/
public class Presenter implements ViewListener {
private final View view;
private final Model model;
@Override
public void onButtonClicked() {
// Update the model (ie. the state of the application)
model.addOneToCount();
// Update the view
view.setLabelText(String.valueOf(model.getCount()));
}
}
To put everything together, the view can be created and injected into the presenter. Similarly, an
initial model can be created and injected. While both can be created in the presenter, injecting
them into the constructor allows for much simpler testing.
https://riptutorial.com/ 33
Chapter 10: StyledDocument
Syntax
• doc.insertString(index, text, attributes); //attributes should be a AttributeSet
Examples
Creating a DefaultStyledDocument
try {
StyledDocument doc = new DefaultStyledDocument();
doc.insertString(0, "This is the beginning text", null);
doc.insertString(doc.getLength(), "\nInserting new line at end of doc", null);
MutableAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setBold(attrs, true);
doc.insertString(5, "This is bold text after 'this'", attrs);
} catch (BadLocationException ex) {
//handle error
}
DefaultStyledDocuments will probably be your most used resources. They can be created directly,
and subclass the StyledDocument abstract class.
try {
JTextPane pane = new JTextPane();
StyledDocument doc = new DefaultStyledDocument();
doc.insertString(0, "Some text", null);
pane.setDocument(doc); //Technically takes any subclass of Document
} catch (BadLocationException ex) {
//handle error
}
Copying DefaultStyledDocument
StyledDocuments generally do not implement clone, and so have to copy them in a different way if
that is necessary.
try {
//Initialization
DefaultStyledDocument sourceDoc = new DefaultStyledDocument();
DefaultStyledDocument destDoc = new DefaultStyledDocument();
MutableAttributeSet bold = new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
MutableAttributeSet italic = new SimpleAttributeSet();
https://riptutorial.com/ 34
StyleConstants.setItalic(italic, true);
sourceDoc.insertString(0, "Some bold text. ", bold);
sourceDoc.insertString(sourceDoc.getLength(), "Some italic text", italic);
try {
DefaultStyledDocument writeDoc = new DefaultStyledDocument();
writeDoc.insertString(0, "Test string", null);
https://riptutorial.com/ 35
Chapter 11: Swing Workers and the EDT
Syntax
• public abstract class SwingWorker<T,V>
• T - the result type returned by this SwingWorker's doInBackground and get methods.
• V - the type used for carrying out intermediate results by this SwingWorker's publish and
process methods.
Examples
Main and event dispatch thread
Like any other java program, every swing program starts with a main method. The main method is
initiated by the main thread. However, Swing components need to be created and updated on the
event dispatch thread (or short: EDT). To illustrate the dynamic between the main thread and the
EDT take a look at this Hello World! example.
The main thread is just used to delegate the creation of the window to the EDT. If the EDT is not
initiated yet, the first call to SwingUtilities.invokeLater will setup the necessary infrastructure for
processing Swing components. Furthermore, the EDT remains active in the background. The main
thread is going to die directly after initiating the EDT setup, but the EDT will remain active until the
user exits the program. This can be achieved by hitting the close box on the visible JFrame
instance. This will shutdown the EDT and the program's process is going to entirely.
Find the first N even numbers and display the results in a JTextArea where
computations are done in background.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
https://riptutorial.com/ 36
PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
this.numbersToFind = numbersToFind;
this.textArea = textArea;
}
@Override
public List<Integer> doInBackground() {
final List<Integer> result = new ArrayList<>();
boolean interrupted = false;
for (int i = 0; !interrupted && (i < numbersToFind); i += 2) {
interrupted = doIntenseComputing();
result.add(i);
publish(i); // sends data to process function
}
return result;
}
@Override
protected void process(List<Integer> chunks) {
for (int number : chunks) {
// the process method will be called on the EDT
// thus UI elementes may be updated in here
textArea.append(number + "\n");
}
}
}
public SwingWorkerExample() {
super("Java SwingWorker Example");
init();
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
https://riptutorial.com/ 37
EventQueue.invokeLater(() -> {
ui.setVisible(true);
});
int n = 100;
PrimeNumbersTask task = new PrimeNumbersTask(ui.textArea, n);
task.execute(); // run async worker which will do long running task on a
// different thread
System.out.println(task.get());
}
}
https://riptutorial.com/ 38
Chapter 12: timer in JFrame
Examples
Timer In JFrame
Suppose you have a button in your Java program that counts down a time. Here is the code for 10
minutes timer.
@Override
public void actionPerformed(ActionEvent e) {
if (cnt > 0) {
cnt = cnt - 1000;
btnCounter.setText("Remained (" + format.format(new Date(cnt)) + ")");
} else {
cnt = REFRESH_LIST_PERIOD;
//TODO
}
}
});
timer.start();
https://riptutorial.com/ 39
Chapter 13: Using Look and Feel
Examples
Using system L&F
https://riptutorial.com/ 40
content.add ( new JButton ( "Native-looking button" ) );
frame.setContentPane ( content );
frame.setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
} );
}
}
Other Solaris,
Motif com.sun.java.swing.plaf.motif.MotifLookAndFeel
Linux
Windows
Windows Vista com.sun.java.swing.plaf.windows.WindowsLookAndFeel
Vista
HP UX HP javax.swing.plaf.synth.SynthLookAndFeel *
* these L&Fs are supplied by system vendor and actual L&F class name might vary
https://riptutorial.com/ 41
{
// Installing custom L&F as a current application L&F
UIManager.setLookAndFeel ( "javax.swing.plaf.metal.MetalLookAndFeel" );
}
catch ( final ClassNotFoundException e )
{
// L&F class was not found
e.printStackTrace ();
}
catch ( final InstantiationException e )
{
// Exception while instantiating L&F class
e.printStackTrace ();
}
catch ( final IllegalAccessException e )
{
// Class or initializer isn't accessible
e.printStackTrace ();
}
catch ( final UnsupportedLookAndFeelException e )
{
// L&F is not supported on the current system
e.printStackTrace ();
}
You can find a huge list of available Swing L&Fs in the topic here: Java Look and Feel (L&F)
Keep in mind that some of those L&Fs might be quite outdated at this point.
https://riptutorial.com/ 42
Chapter 14: Using Swing for Graphical User
Interfaces
Remarks
Examples
Creating an Empty Window (JFrame)
frame.setSize(512, 256);
https://riptutorial.com/ 43
Or you can have the frame size itself based on the size of its contents with the pack() method.
frame.pack();
The setSize() and pack() methods are mutually exclusive, so use one or the other.
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Alternatively, you can tell the window to do something else when it is closed.
frame.setVisible(true);
Example
For those of you who like to copy and paste, here's some example code.
JFrame frame = new JFrame("Super Awesome Window Title!"); //Create the JFrame and give it a
title
frame.setSize(512, 256); //512 x 256px size
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Quit the application when the
https://riptutorial.com/ 44
JFrame is closed
Adding Components
A component is some sort of user interface element, such as a button or a text field.
Creating a Component
Creating components is near identical to creating a window. Instead of creating a JFrame however,
you create that component. For example, to create a JButton, you do the following.
Many components can have parameters passed to them when created. For example, a button can
be given some text to display.
If you don't want to create a button, a list of common components can be found in another
example on this page.
The parameters that can be passed to them vary from component to component. A good way of
checking what they can accept is by looking at the paramters within your IDE (If you use one). The
https://riptutorial.com/ 45
default shortcuts are listed below.
Example
Here's an example of creating a window, setting a content pane, and adding a button to it.
JFrame frame = new JFrame("Super Awesome Window Title!"); //Create the JFrame and give it a
title
frame.setSize(512, 256); //512 x 256px size
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Quit the application when the
JFrame is closed
https://riptutorial.com/ 46
Setting Parameters for Components
Components have various parameters that can be set for them. They vary from component to
component, so a good way to see what parameters can be set for components is to start typing
componentName.set, and let your IDE's autocomplete (If you use an IDE) suggest methods. The
default shortcut in many IDEs, if it doesn't show up automatically, is CTRL + Space.
Description Method
Sets the smallest size that the component can be (only if setMinimumSize(Dimension
the layout manager honors the minimumSize property) minimumSize)
https://riptutorial.com/ 47
Description Method
Sets the biggest size that the component can be (only if setMaximumSize(Dimension
the layout manager honors the maximumSize property) maximumSize)
Sets whether the component should respond to user input setEnabled(boolean enabled)
Common Components
Description Class
Button JButton
https://riptutorial.com/ 48
Description Class
Checkbox JCheckBox
Label JLabel
List JList
Panel JPanel
Slider JSlider
Table JTable
Tree JTree
Having a button there is all well and good, but what's the point if clicking it does nothing?
ActionListeners are used to tell your button, or other component to do something when it is
activated.
buttonA.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Code goes here...
System.out.println("You clicked the button!");
https://riptutorial.com/ 49
}
});
buttonA.addActionListener(e -> {
//Code
System.out.println("You clicked the button!");
});
Adding components one after another results in a UI that's hard to use, because the components
all are somewhere. The components are ordered from top to bottom, each component in a
separate "row".
To remedy this and provide you as developer with a possibility to layout components easily Swing
has LayoutManagers.
These LayoutManagers are covered more extensively in Introduction to Layout Managers as well
as the separate Layout Manager topics:
• Grid Layout
• GridBag Layout
https://riptutorial.com/ 50
Credits
S.
Chapters Contributors
No
https://riptutorial.com/ 51