Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Swing Component API Reference and Implementation Guide

Tech 1

Text Component API Overview

The text component API encompasses functionality shared across all Swing text components. Most of this API is defined within the JTextComponent class hierarchy. This section categorizes the essential APIs for text manipulation.

Property Management

The following methods control fundamental text component behavior:

Method Purpose
void setEditable(boolean) / boolean isEditable() Controls whether user can modify text content
void setDragEnabled(boolean) / boolean getDragEnabled() Enables drag-and-drop operations (default: false)
void setDisabledTextColor(Color) / Color getDisabledTextColor() Specifies text color when component is disabled
void setMargin(Insets) / Insets getMargin() Defines spacing between text and component border

Selection Operations

Method Purpose
String getSelectedText() Retrieves currently selected text
void selectAll() / void select(int, int) Selects all content or a specific range
void setSelectionStart(int) / void setSelectionEnd(int) Defines selection boundaries by index
int getSelectionStart() / int getSelectionEnd() Retrieves selection boundaries
void setSelectedTextColor(Color) / Color getSelectedTextColor() Controls color of selected text
void setSelectionColor(Color) / Color getSelectionColor() Controls background color of selection

Coordinate Transformation

Method Purpose
int viewToModel(Point) Converts view coordinates to document position
Rectangle modelToView(int) Converts document position to view rectangle

Text Editing Operations

Class/Method Description
void cut() / void copy() / void paste() Clipboard operations
void replaceSelection(String) Replaces selection with specified text
EditorKit Provides view factories, documents, carets, and I/O for specific formats
DefaultEditorKit Concrete implementation offering basic editing capabilities
StyledEditorKit Extends DefaultEditorKit for styled text support

Document Representation

Interface/Class Description
Document Interface defining document API contract
AbstractDocument Abstract base implementation for all Swing documents
PlainDocument Default document for plain text components
StyledDocument Subinterface supporting styled text
DefaultStyledDocument Implementation used by JTextPane

Caret and Highlighting

Interface/Class Description
Caret Interface for insertion point representation
DefaultCaret Default caret implementation for all text components
void setCaret(Caret) / Caret getCaret() Manages caret instance
void setCaretColor(Color) / Color getCaretColor() Controls caret color
Highlighter Interface for selection highlighting
DefaultHighlighter Default implementation for text highlighting

Building Swing Applets

Swing applets extend JApplet, which subclasses java.applet.Applet. Any applet containing Swing components must implement a JApplet subclass.

Applet Initialization Pattern

Swing components must be created, queried, and manipulated on the Event Dispatch Thread (EDT). The applet lifecycle methods—init, start, stop, and destroy—do not execute on the EDT by default. Use SwingUtilities.invokeAndWait() to ensure Swing code runs on the EDT:

public void init() {
    try {
        javax.swing.SwingUtilities.invokeAndWait(() -> initializeUI());
    } catch (Exception e) {
        System.err.println("UI initialization failed: " + e.getMessage());
    }
}

private void initializeUI() {
    JLabel statusLabel = new JLabel("Swing applet loaded successfully");
    statusLabel.setHorizontalAlignment(JLabel.CENTER);
    getContentPane().add(statusLabel, BorderLayout.CENTER);
}

Loading Images in Applets

For loading image resources efficiently, use getResourceAsStream rather than getResource when deploying via JAR files:

private ImageIcon loadFrameImage(int frameNumber) {
    String resourcePath = "/images/animation_" + frameNumber + ".gif";
    int maxFileSize = 2400;
    
    try (BufferedInputStream imageStream = 
            new BufferedInputStream(getClass().getResourceAsStream(resourcePath))) {
        
        if (imageStream == null) {
            System.err.println("Resource not found: " + resourcePath);
            return null;
        }
        
        byte[] imageData = new byte[maxFileSize];
        int bytesRead = imageStream.read(imageData);
        
        if (bytesRead <= 0) {
            return null;
        }
        
        return new ImageIcon(Toolkit.getDefaultToolkit().createImage(imageData));
    } catch (IOException e) {
        return null;
    }
}

JApplet API Reference

Method Purpose
void setContentPane(Container) / Container getContentPane() Manages content pane containing visible components
void setRootPane(JRootPane) / JRootPane getRootPane() Accesses root pane managing internal layout
void setJMenuBar(JMenuBar) / JMenuBar getMenuBar() Sets application menu bar
void setGlassPane(Component) / Component getGlassPane() Manages glass pane for event interception
void setLayeredPane(JLayeredPane) / JLayeredPane getLayeredPane() Controls layered component positioning

Button Components

Swing provides various button types through AbstractButton subclasses:

Class Use Case
JButton Standard action button
JCheckBox Toggle selection option
JRadioButton Grouped mutually-exclusive selection
JMenuItem Menu command
JCheckBoxMenuItem Menu option with check state
JRadioButtonMenuItem Menu option with radio behavior
JToggleButton Two-state button (base for CheckBox/RadioButton)

Button Implementation Example

public class ButtonPanel extends JPanel {
    private JButton disableButton;
    private JButton enableButton;
    private JToggleButton middleButton;

    public ButtonPanel() {
        setLayout(new FlowLayout());
        initializeButtons();
    }

    private void initializeButtons() {
        disableButton = new JButton("Disable Middle", createIcon("left.gif"));
        disableButton.setVerticalTextPosition(AbstractButton.CENTER);
        disableButton.setHorizontalTextPosition(AbstractButton.LEADING);
        disableButton.setMnemonic(KeyEvent.VK_D);
        disableButton.setActionCommand("disable");

        middleButton = new JToggleButton("Middle Toggle");
        middleButton.setMnemonic(KeyEvent.VK_M);

        enableButton = new JButton("Enable Middle", createIcon("right.gif"));
        enableButton.setMnemonic(KeyEvent.VK_E);
        enableButton.setActionCommand("enable");
        enableButton.setEnabled(false);

        disableButton.addActionListener(e -> handleButtonAction(e));
        enableButton.addActionListener(e -> handleButtonAction(e));

        add(disableButton);
        add(middleButton);
        add(enableButton);
    }

    private void handleButtonAction(ActionEvent event) {
        String command = event.getActionCommand();
        if ("disable".equals(command)) {
            middleButton.setEnabled(false);
            disableButton.setEnabled(false);
            enableButton.setEnabled(true);
        } else {
            middleButton.setEnabled(true);
            disableButton.setEnabled(true);
            enableButton.setEnabled(false);
        }
    }

    private ImageIcon createIcon(String path) {
        URL iconUrl = getClass().getResource("images/" + path);
        return iconUrl != null ? new ImageIcon(iconUrl) : null;
    }
}

ButtonGroup for Radio Buttons

Use ButtonGroup to enforce single-selection behavior among radio buttons:

private void setupRadioGroup() {
    ButtonGroup animalGroup = new ButtonGroup();
    
    JRadioButton birdOption = new JRadioButton("Bird");
    birdOption.setMnemonic(KeyEvent.VK_B);
    birdOption.setSelected(true);
    
    JRadioButton catOption = new JRadioButton("Cat");
    catOption.setMnemonic(KeyEvent.VK_C);
    
    JRadioButton dogOption = new JRadioButton("Dog");
    dogOption.setMnemonic(KeyEvent.VK_D);
    
    animalGroup.add(birdOption);
    animalGroup.add(catOption);
    animalGroup.add(dogOption);
}

Color Chooser Implementation

JColorChooser provides a complete color selection interface with multiple selection models:

Basic Color Chooser Setup

public class ColorSelectionPanel extends JPanel {
    private JLabel previewLabel;
    private JColorChooser colorPicker;

    public ColorSelectionPanel() {
        super(new BorderLayout(10, 10));
        initializeComponents();
    }

    private void initializeComponents() {
        previewLabel = new JLabel("Preview Text Color", JLabel.CENTER);
        previewLabel.setForeground(Color.YELLOW);
        previewLabel.setBackground(Color.BLACK);
        previewLabel.setOpaque(true);
        
        colorPicker = new JColorChooser(previewLabel.getForeground());
        colorPicker.getSelectionModel().addChangeListener(this::handleColorChange);
        
        add(previewLabel, BorderLayout.PAGE_START);
        add(colorPicker, BorderLayout.CENTER);
    }

    private void handleColorChange(ChangeEvent event) {
        ColorSelectionModel model = (ColorSelectionModel) event.getSource();
        previewLabel.setForeground(model.getSelectedColor());
    }
}

Custom Chooser Panel

Extend AbstractColorChooserPanel to create custom color selection interfaces:

public class CrayonColorPanel extends AbstractColorChooserPanel {
    private JToggleButton redCrayon, yellowCrayon, greenCrayon, blueCrayon;
    
    @Override
    protected void buildChooser() {
        setLayout(new GridLayout(2, 2));
        
        redCrayon = new JToggleButton("Red");
        redCrayon.setBackground(Color.RED);
        add(redCrayon);
        
        yellowCrayon = new JToggleButton("Yellow");
        yellowCrayon.setBackground(Color.YELLOW);
        add(yellowCrayon);
        
        greenCrayon = new JToggleButton("Green");
        greenCrayon.setBackground(Color.GREEN);
        add(greenCrayon);
        
        blueCrayon = new JToggleButton("Blue");
        blueCrayon.setBackground(Color.BLUE);
        add(blueCrayon);
    }

    @Override
    public void updateChooser() {
        Color current = getColorFromModel();
        redCrayon.setSelected(Color.RED.equals(current));
        yellowCrayon.setSelected(Color.YELLOW.equals(current));
        greenCrayon.setSelected(Color.GREEN.equals(current));
        blueCrayon.setSelected(Color.BLUE.equals(current));
    }

    @Override
    public String getDisplayName() {
        return "Crayons";
    }
}

Color Chooser API

Method Purpose
JColorChooser() / JColorChooser(Color) Create chooser with optional initial color
Color showDialog(Component, String, Color) Display modal color selection dialog
void setPreviewPanel(JComponent) Customize or remove preview area
void setChooserPanels(AbstractColorChooserPanel[]) Replace default selector panels
void addChooserPanel(AbstractColorChooserPanel) Add custom panel to chooser
void setSelectionModel(ColorSelectionModel) Manage color selection model

Combo Box Components

JComboBox provides either editable or non-editable dropdown selection:

Non-Editable Combo Box

public class SelectionComboBox extends JPanel {
    private JComboBox<String> animalSelector;
    private JLabel imageDisplay;

    public SelectionComboBox() {
        setLayout(new BorderLayout(5, 5));
        initializeControls();
    }

    private void initializeControls() {
        String[] animals = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
        
        animalSelector = new JComboBox<>(animals);
        animalSelector.setSelectedIndex(4);
        animalSelector.addActionListener(this::handleSelection);
        
        imageDisplay = new JLabel();
        imageDisplay.setHorizontalAlignment(JLabel.CENTER);
        
        add(animalSelector, BorderLayout.PAGE_START);
        add(imageDisplay, BorderLayout.CENTER);
    }

    private void handleSelection(ActionEvent event) {
        String selected = (String) animalSelector.getSelectedItem();
        imageDisplay.setIcon(new ImageIcon("images/" + selected.toLowerCase() + ".gif"));
    }
}

Editable Combo Box with Custom Renderer

public class CustomComboBoxRenderer extends JLabel 
        implements ListCellRenderer<Object> {
    
    private final ImageIcon[] itemIcons;
    private final String[] itemLabels;

    public CustomComboBoxRenderer(ImageIcon[] icons, String[] labels) {
        this.itemIcons = icons;
        this.itemLabels = labels;
        setOpaque(true);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value,
            int index, boolean isSelected, boolean hasFocus) {
        
        int selectedIndex = ((Integer) value).intValue();
        
        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }
        
        ImageIcon icon = itemIcons[selectedIndex];
        setIcon(icon);
        setText(itemLabels[selectedIndex]);
        setFont(list.getFont());
        
        return this;
    }
}

Dialog Implementation

Simple Message Dialogs

// Information dialog
JOptionPane.showMessageDialog(frame, 
    "Operation completed successfully.",
    "Success",
    JOptionPane.INFORMATION_MESSAGE);

// Warning dialog  
JOptionPane.showMessageDialog(frame,
    "Disk space is running low.",
    "Warning",
    JOptionPane.WARNING_MESSAGE);

// Error dialog
JOptionPane.showMessageDialog(frame,
    "Failed to connect to server.",
    "Error",
    JOptionPane.ERROR_MESSAGE);

Custom Option Dialog

public class CustomOptionDialog extends JPanel {
    private JLabel resultLabel;

    public CustomOptionDialog() {
        String[] options = {"Yes, please", "No, thanks", "Maybe later"};
        
        int userChoice = JOptionPane.showOptionDialog(
            this,
            "Would you like to save your changes?",
            "Save Confirmation",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]
        );
        
        handleUserResponse(userChoice);
    }

    private void handleUserResponse(int choice) {
        switch (choice) {
            case JOptionPane.YES_OPTION:
                // Save and close
                break;
            case JOptionPane.NO_OPTION:
                // Discard and close
                break;
            case JOptionPane.CANCEL_OPTION:
            case JOptionPane.CLOSED_OPTION:
                // Cancel operation
                break;
        }
    }
}

Preventing Auto-Close Behavior

To prevent dialog from closing automatically until validation passes:

public void showBlockingDialog(JFrame parent) {
    JOptionPane optionPane = new JOptionPane(
        "Please confirm your selection before proceeding.",
        JOptionPane.QUESTION_MESSAGE,
        JOptionPane.YES_NO_OPTION
    );

    JDialog dialog = new JDialog(parent, "Confirm", true);
    dialog.setContentPane(optionPane);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

    optionPane.addPropertyChangeListener(event -> {
        if (dialog.isVisible() 
                && event.getSource() == optionPane
                && JOptionPane.VALUE_PROPERTY.equals(event.getPropertyName())) {
            
            int selectedValue = ((Integer) optionPane.getValue()).intValue();
            
            if (validateSelection(selectedValue)) {
                dialog.setVisible(false);
            } else {
                optionPane.setValue(JOptionPane.UNDEFINED_CONVERSION);
            }
        }
    });

    dialog.pack();
    dialog.setLocationRelativeTo(parent);
    dialog.setVisible(true);
}

private boolean validateSelection(int value) {
    return value != JOptionPane.CANCEL_OPTION;
}

Dialog API Reference

Method Purpose
showMessageDialog(Component, Object, String, int, Icon) Display informational dialog
showConfirmDialog(Component, Object, String, int, int, Icon) Request user confirmation
showInputDialog(Component, Object, String, int, Icon, Object[], Object) Prompt for user input
showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) Display custom button options
createDialog(Component, String, boolean, JColorChooser, ActionListener, ActionListener) Create custom dialog with buttons
Tags: JavaSwing

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.