Use BorderLayout to arrange components around a central area. It works well for a window with a header at the top, a status bar at the bottom, and content in the middle.
In this example, you will place a button in each of the five regions and see how they resize with the window.
Source code
Save the following code as BorderLayoutExample.java:
new BorderLayout(8, 8) sets an 8-pixel horizontal gap and an 8-pixel vertical gap between neighboring components. The empty border adds 12 pixels of padding around the panel.
The second argument to panel.add() selects the region:
Stretch horizontally and keep their preferred height
WEST and EAST
Stretch vertically between the top and bottom regions and keep their preferred width
CENTER
Fills the space left over in both directions
Each region holds one component. To place several controls in the same region, put them in a JPanel and add that panel to the region. For example, a header panel might contain a title and several buttons.
Drag the right edge of the window outward. The North, Center, and South buttons grow wider, while West and East keep their widths. Then drag the bottom edge downward: West, Center, and East grow taller.
Use JOptionPane.showMessageDialog() to display a short message with an OK button. This example opens an information dialog without creating a separate JFrame.
Source code
Save the following code as MessageDialogExample.java:
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class MessageDialogExample {
void main() {
SwingUtilities.invokeLater(this::showMessage);
}
private void showMessage() {
JOptionPane.showMessageDialog(
null,
"Hello from Swing!",
"Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
What the dialog looks like
The icon and window styling depend on your system and Swing look and feel.
Explanation
The showMessageDialog() call uses four arguments:
Argument
Purpose
null
Shows the dialog without positioning it relative to an existing component
"Hello from Swing!"
Sets the message shown inside the dialog
"Message"
Sets the title shown in the title bar
JOptionPane.INFORMATION_MESSAGE
Selects the information message type, which usually displays an information icon
If your application already has a window, pass its JFrame instead of null so Swing can position the dialog relative to that window.
SwingUtilities.invokeLater() schedules showMessage() on Swing’s event dispatch thread. The dialog is modal, so the call to showMessageDialog() returns after the user dismisses the dialog. It returns no value. If you need to ask a question and read the user’s choice, use showConfirmDialog().
You can create blobs that appear to merge by adding together scalar fields and coloring pixels according to the total. In this SwingLoops example, five moving centers produce luminous shapes that join and separate without collision detection or a fluid engine.
Metaball Fusion
Source code
Save this code as MetaballFusion.java:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class MetaballFusion extends JPanel {
private static final int W = 180, H = 320, COUNT = 5;
private static final double CYCLE = 12.0;
private final BufferedImage image =
new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
private final int[] pixels =
((DataBufferInt) image.getRaster().getDataBuffer()).getData();
private final double[] cx = new double[COUNT], cy = new double[COUNT];
private final Timer timer = new Timer(33, _ -> repaint());
private long start;
public MetaballFusion() {
setPreferredSize(new Dimension(450, 800));
setBackground(new Color(6, 11, 24));
}
@Override public void addNotify() {
super.addNotify();
start = System.nanoTime();
timer.start();
}
@Override public void removeNotify() {
timer.stop();
super.removeNotify();
}
private static double smooth(double a, double b, double x) {
double u = Math.max(0, Math.min(1, (x - a) / (b - a)));
return u * u * (3 - 2 * u);
}
private void render(double seconds) {
double phase = 2 * Math.PI * (seconds % CYCLE) / CYCLE;
for (int i = 0; i < COUNT; i++) {
double offset = i * 2 * Math.PI / COUNT;
cx[i] = W / 2.0 + 48 * Math.cos(phase + offset);
cy[i] = H / 2.0 + 70 * Math.sin(2 * phase + offset);
}
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
double field = 0;
for (int i = 0; i < COUNT; i++) {
double dx = x - cx[i], dy = y - cy[i];
field += 196.0 / (dx * dx + dy * dy + 1);
}
double fill = smooth(0.94, 1.06, field);
double edge = Math.exp(-Math.pow((field - 1) / 0.12, 2));
double inside = fill * (0.58 + 0.25 *
Math.sin(x * 0.035 + y * 0.02 + phase));
int red = (int) Math.min(255, 6 + 48 * inside + 116 * edge);
int green = (int) Math.min(255, 11 + 192 * inside + 150 * edge);
int blue = (int) Math.min(255, 24 + 210 * inside + 170 * edge);
pixels[y * W + x] = (red << 16) | (green << 8) | blue;
}
}
}
@Override protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
render((System.nanoTime() - start) / 1e9);
Graphics2D g = (Graphics2D) graphics.create();
try {
double scale = Math.min(getWidth() / (double) W,
getHeight() / (double) H);
g.translate((getWidth() - W * scale) / 2,
(getHeight() - H * scale) / 2);
g.scale(scale, scale);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, null);
} finally {
g.dispose();
}
}
static void main() {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("SwingLoops - Metaball Fusion");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new MetaballFusion());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Run the example
Install a JDK and use a desktop environment that supports Swing. In the directory containing the source file, run:
javac MetaballFusion.java
java MetaballFusion
Build a scalar field
At each pixel, the program calculates the distance from each moving center and adds a contribution:
field += 196.0 / (dx * dx + dy * dy + 1);
A nearby center contributes a large value; a distant center contributes less. The added one prevents division by zero at a center.
The visible surface is defined by a field value near one. For an isolated center, that value would occur at a distance of approximately 14 pixels. The combined fields of neighboring centers enlarge and deform that boundary.
Why do the blobs merge?
Suppose a pixel between two centers receives 0.6 from each. Neither contribution reaches the threshold on its own, but their sum is 1.2. That pixel belongs to the filled region.
As the centers approach, more pixels between them cross the threshold and form a connecting neck. When they separate, those pixels fall below the threshold again. The program does not need a special instruction to join or split shapes.
Color the boundary
A smoothstep function changes the fill from zero to one over the interval 0.94–1.06:
double fill = smooth(0.94, 1.06, field);
A narrow Gaussian-shaped function adds a bright edge around the threshold:
Its value is greatest when the field equals one and decreases on either side. This is a glow in field-value space rather than a constant-width blur in screen pixels.
The interior also uses a gentle sinusoidal color variation. The final RGB channels are clamped before being packed into an integer pixel.
Move the centers
Each center follows a sinusoidal path with a different phase offset:
The vertical motion completes two oscillations for each horizontal oscillation. After 12 seconds, both coordinates and the interior coloring return to their starting states.
Render with Swing
The calculation runs at 180 × 320 pixels to limit per-frame work. A BufferedImage backed by an integer array lets the program write colors directly. Java 2D scales the image with bilinear interpolation for display.
A Swing timer requests repaints approximately every 33 milliseconds. Motion depends on elapsed time, not the number of frames. The interface and painting run on the event-dispatch thread. More fields or a higher internal resolution increase painting work and may reduce responsiveness.
Customize the effect
Try increasing the strength from 196 to 256. Because the boundary depends on the sum, this makes the blobs larger and encourages merging. Then increase the horizontal orbit amplitude from 48 to 60 to pull them farther apart.
This example is an artistic field visualization, not a simulation of liquid pressure or surface tension. The complete source is free to copy and run.
Call getText() on a JTextField to read what the user has typed. In this example, the user enters a name and clicks Say hello or presses Enter to display a greeting.
Source code
Save the following code as TextFieldExample.java:
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class TextFieldExample {
void main() {
SwingUtilities.invokeLater(this::showWindow);
}
private void showWindow() {
JTextField nameField = new JTextField(14);
JLabel nameLabel = new JLabel("Name:");
nameLabel.setLabelFor(nameField);
JButton greetButton = new JButton("Say hello");
JLabel greeting = new JLabel(
"Enter your name.", SwingConstants.CENTER);
greetButton.addActionListener(event ->
updateGreeting(nameField, greeting));
nameField.addActionListener(event ->
updateGreeting(nameField, greeting));
JPanel form = new JPanel();
form.add(nameLabel);
form.add(nameField);
form.add(greetButton);
JPanel content = new JPanel(new BorderLayout(0, 12));
content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
content.add(form, BorderLayout.PAGE_START);
content.add(greeting, BorderLayout.CENTER);
JFrame frame = new JFrame("Text Field Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void updateGreeting(JTextField nameField, JLabel greeting) {
String name = nameField.getText().strip();
if (name.isEmpty()) {
greeting.setText("Please enter your name.");
} else {
greeting.setText("Hello, " + name + "!");
}
}
}
What the window looks like
Explanation
new JTextField(14) creates a single-line text field. The number 14 helps Swing calculate its preferred width. The user can still type more than 14 characters.
The updateGreeting() method reads the field when the user submits the name:
String name = nameField.getText().strip();
getText() returns the current text. strip() removes whitespace from both ends of the returned string without changing what appears in the field. If the result is empty, the label asks for a name. Otherwise, it displays a greeting.
Both the button and the text field have an action listener that calls updateGreeting(). The button listener runs when the button is activated. The text field listener runs when the user presses Enter while the field has focus. Both listeners run on Swing’s event dispatch thread and can update the label directly.
Run the example
javac TextFieldExample.java
java TextFieldExample
Type Rosa and click Say hello. The label displays Hello, Rosa!. Clear the field and press Enter to see Please enter your name.
addActionListener() registers a listener that Swing calls when the button is activated. The lambda is the listener in this example. Its event parameter receives information about the action, but the example only needs to update the label, so it does not use that parameter.
When the listener runs, message.setText() changes the existing label. It works whether you click the button with a mouse or activate it with the keyboard.
SwingUtilities.invokeLater() creates the window on the event dispatch thread. Swing also runs the listener on that thread, so it can update the label directly. Keep listeners short so the window stays responsive.