SoFunction
Updated on 2025-04-13

Sample code for Java implementing PIFrame form effects

1. Project Introduction

This project implements a custom "PIFrame" form effect, and its main features include:

  • Borderless form: The form does not use the operating system default border, but uses custom drawing.
  • Transparent and rounded corner effects: Make the form more fashionable by setting the transparency of the form and drawing the rounded corners.
  • Shadow effect: Add form shadows to enhance three-dimensionality and visual hierarchy.
  • Custom drag and drop: Since the borderless form cannot be dragged by default, it is necessary to implement the mouse drag event by itself, and the form movement is supported.

Through these effects, forms similar to "Picture-in-Picture" or personalized customization can be created to provide users with a richer interactive experience.

2. Project background and requirements analysis

background

In many modern applications (such as video players, desktop gadgets, taskbar tools, etc.), it is often necessary to use a personalized form appearance to get rid of the limitations of traditional window borders. Borderless, transparent, rounded corners and shadow effects make the form appear lighter and more visually attractive, while allowing users to freely drag and dock the form. Although Java Swing provides basic borderless form support (via setUndecorated(true)), more custom drawing and event processing are required for more advanced visual effects.

need

The main requirements of this project include:

  1. Borderless, transparent form

    • Create a borderless form (JFrame) and set partial transparent effects and rounded corner effects to get it out of traditional form style.
  2. Shadow effect

    • Achieve the form shadow effect and simulate the three-dimensional floating feeling.
  3. Custom drag and drop

    • Implement mouse drag event, allowing users to move by dragging and dropping custom forms.
  4. Parameterized settings

    • Supports setting form transparency, rounded corner radius and shadow parameters for easier subsequent expansion and adjustment.
  5. Modular design

    • The MVC idea is used to separate interface display, visual effect drawing and interactive logic, which is easy to maintain and expand.

3. Introduction to related knowledge

3.1 Java Swing and AWT Basics

  • Swing Components
    ——Java Swing is a lightweight component library that supports highly customized form design, and all components are inherited from JComponent.

  • AWT Event Model
    —— Event listeners (such as MouseListener, MouseMotionListener) can be used to capture mouse operations and implement custom drag and drop functions.

3.2 Borderless forms and custom decorations

  • setUndecorated(true)
    ——JFrame provides the setUndecorated(true) method, which can remove the default title bar and border of the system, making the form a borderless state.

  • Custom decoration
    ——In the borderless state, you can customize drawing and add additional components to achieve title bars, close buttons, and other decorations.

3.3 Transparent and rounded form effects

  • Form transparency
    —— Starting from Java 6 Update 10, Swing supports setting window transparency (setOpacity method), allowing developers to make semi-transparent forms.

  • Rounded corner effect
    ——Rewrite the paintComponent() method of the form or use the WindowShape API (setShape) to set the rounded corner shape to achieve the form rounded corner effect.

3.4 Shadow effect implementation

  • Draw shadows
    ——By drawing rectangles with blurred edges or using third-party libraries, the form shadow effect can be achieved and the three-dimensional sense can be enhanced.

  • Custom drawing
    ——Use Graphics2D objects for anti-aliasing and gradient filling to draw soft shadow effects.

3.5 Application of MVC mode in form design

  • Model (model)
    ——Storing the relevant parameters of form effect (transparency, rounded corner radius, shadow parameters, etc.).

  • View (view)
    ——Composed of a custom JFrame, responsible for displaying borderless, transparent, rounded, and shadowed forms.

  • Controller
    —— Handle events such as mouse drag and drop, button clicks, update the form position and status, and coordinate the data interaction between the model and the view.

4. Project implementation ideas and design plans

4.1 System architecture and design concepts

This project adopts the MVC architecture design and divides the PIFrame form effect into three parts:

  • Model: Save the appearance parameters of the form, such as transparency, rounded corner radius, shadow offset and blur.
  • view: Create a borderless JFrame, use setUndecorated(true) to remove system borders, and achieve rounded corners and transparent effects through setShape() and setOpacity().
  • Controller: Handle mouse drag events so that the form can move freely, and is responsible for updating the form status.

4.2 Class design and division of responsibilities

This project mainly involves the following categories:

  1. PIFrameDemo

    • Program entry class, create the main window and start the PIFrame form effect example.
  2. PIFrame

    • Custom form class, inherited from JFrame.
    • Call setUndecorated(true) in the constructor to set borderless, realize rounded corners through setShape(), set transparency through setOpacity(), and add custom shadow drawing (optional).
    • Add a mouse event listener to drag and move the form.
  3. VibrationUtil (optional)

    • If additional interactive effects are needed (such as form vibration prompts), the relevant code can be encapsulated as a tool class, but this project focuses on form visual effects and drag and move.

4.3 Analysis of key technical points

  1. Borderless form

    • Use setUndecorated(true) to create a borderless form, removing the default title bar and border.
  2. Transparent and rounded corners effect of form

    • Call the setOpacity() method to set the form transparency (note: related features need to be enabled on some platforms).
    • Use the setShape(new (...)) method to set the form shape to a rounded rectangle to achieve the rounded corner effect.
  3. Shadow effect

    • The form shadow effect can be achieved by drawing a shadow panel or calling a third-party library. In this example, you can simulate a simple shadow effect by drawing a background.
  4. Mouse drag and move

    • Add MouseListener and MouseMotionListener to the form, record the starting click position in mousePressed, calculate the new window position in mouseDragged and call setLocation() to update the form position, realizing drag and drop movement.

5. Project implementation code

The following is a complete example code that implements a PIFrame form effect with rounded corners, transparent and draggable. The code contains detailed Chinese comments to help you understand the implementation principles of each part.

import .*;
import .*;
import .*;
import .RoundRectangle2D;
 
/**
  * The PIFrameDemo class is a program entry, creating and displaying a custom PIFrame form effect example.
  */
public class PIFrameDemo {
    public static void main(String[] args) {
        // Set the Swing appearance to ensure that the interface is consistent with the operating system        try {
            (());
        } catch(Exception e) {
            ();
        }
        
        (() -> {
            // Create a custom PIFrame form            PIFrame frame = new PIFrame("Custom PIFrame Form");
            (500, 400);
            (null);
            (true);
        });
    }
}
 
/**
  * The PIFrame class is a custom form inherited from JFrame, displaying borderless, transparent, rounded corners and drag-able effects.
  */
class PIFrame extends JFrame {
    // Record the starting position of dragging    private Point initialClick;
    
    public PIFrame(String title) {
        super(title);
        // Remove the default border of the system        setUndecorated(true);
        // Set the form transparency (values ​​0.0 ~ 1.0), note that some platforms may require special configuration        setOpacity(0.95f);
        // Set the rounded corner effect, and achieve it by setting the form shape        setShape(new (0, 0, getWidth(), getHeight(), 30, 30));
        
        // Add sample content        JLabel label = new JLabel("Custom PIFrame Form Effect", );
        (new Font("SansSerif", , 24));
        add(label, );
        
        // Add a mouse event listener to drag and move the form        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                // Record the starting position when the mouse is pressed                initialClick = ();
            }
        });
        
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                // Get the current window location                int thisX = getLocation().x;
                int thisY = getLocation().y;
                // Calculate drag distance                int xMoved = () - ;
                int yMoved = () - ;
                // Calculate the new position and set the window position                int X = thisX + xMoved;
                int Y = thisY + yMoved;
                setLocation(X, Y);
            }
        });
        
        // Add a simple close button (custom form requires custom close button)        JButton closeButton = new JButton("X");
        (false);
        (false);
        (false);
        ();
        (new Font("SansSerif", , 16));
        (e -> (0));
        
        // Add the close button to the upper right corner of the form        JPanel titlePanel = new JPanel(new FlowLayout());
        (false);
        (closeButton);
        add(titlePanel, );
        
        // Optional: Set shadow effect (requires additional shadow form or use third-party libraries)        // This example only shows the basic effects    }
    
    @Override
    public void setSize(int width, int height) {
        (width, height);
        // After each size is set, update the form shape to maintain the rounded corner effect        setShape(new (0, 0, width, height, 30, 30));
    }
}

6. Code interpretation

6.1 Main methods Functional analysis

  • (String[] args)

    • In the program entrance, create the main window, instantiate the custom PIFrame form, and set the size and position before displaying it.
  • PIFrame construction method

    • Call setUndecorated(true) to remove the system default border, and use setOpacity() to set the form transparency to make the form have a semi-transparent effect.
    • Pass the RoundRectangle2D object through the setShape() method to achieve the rounded corner effect of the form.
    • Add content components (such as JLabel display titles) and set the form layout.
    • By adding MouseListener and MouseMotionListener to capture mouse press and drag events, you can realize custom drag and move the window.
    • Customize a close button and place it in the upper right corner of the form to facilitate closing the form.
  • setSize() Rewrite

    • After each time the form size is set, re-call the setShape() method to update the form shape to ensure that the rounded corner effect always fits the current size.

6.2 Analysis of custom form effects

  • Borderless and transparent
    • Use setUndecorated(true) to remove the default form border; setOpacity() to set the form semi-transparent effect to make the form look more modern.
  • Rounded corner effect
    • Pass in to implement the rounded corners of the form through the setShape() method, and the rounded corner radius can be adjusted according to the needs.
  • Drag and move
    • Record the position of the mouse press, calculate the movement offset during the dragging process, update the form position through setLocation() to achieve free dragging.
  • Customize the close button
    • Customize a simple close button and add it to the form's title area to make the borderless form have basic control functions.

7. Project Summary and Prospect

Project Summary

This project shows how to use Java Swing to achieve customized PIFrame form effects, which are mainly reflected in the following aspects:

  1. Borderless form implementation

    • SetUndecorated(true) is used to implement a form without system default borders, laying the foundation for customizing visual effects.
  2. Transparent, rounded corner effect

    • Use the setOpacity() and setShape() methods to achieve the translucent and rounded corner effects of the form, making the interface more modern.
  3. Custom drag and drop and control

    • Add a mouse event listener to realize the free drag and move of the form; the custom close button makes up for the defects of the borderless form.
  4. Modular design

    • Encapsulate form visual effects and interactive logic in the PIFrame class to facilitate subsequent expansion, such as adding shadows, animation effects and state memory.

Outlook and future work

Although this project implements the basic PIFrame form effect, there is still room for expansion in actual applications:

  1. Shadow effect

    • Combined with graphic drawing technology or third-party libraries, the form shadow effect is achieved and the three-dimensional feeling is enhanced.
  2. Animation and interaction optimization

    • Add animation effects when the form is displayed and hidden, as well as a smoother movement experience during dragging and dropping.
  3. Status memory

    • Save the last position and size of the form, restore the last window state when the program restarts, and improve the user experience.
  4. More customization features

    • Add custom title bars, menus, and other controls to make the form personalized not only visually but also provides complete application control.

Overall, this project not only shows how to implement custom PIFrame form effects, but also provides developers with a modular, easy-to-scaling desktop application interface design example. I hope everyone can continue to explore and innovate on this basis and develop more high-quality applications that meet actual needs.

The above is the detailed content of the sample code for Java to implement PIFrame form effects. For more information about Java PIFrame form effects, please pay attention to my other related articles!