您可以使用 GlassPane,也可以简单地将 LayerUI 放在顶部,例如:
当您调整框架大小时,圆圈会重新缩放。
import java.awt.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
/**
*/
public class ALittleSomething {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("A Little Something");
JLayer<JComponent> aLittleSomething = new JLayer<>(new ALittleSomethingPanel(), new ALittleSomethingUI());
frame.getContentPane().add(aLittleSomething);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(800, 450));
frame.setLocationRelativeTo(null); // Center
frame.pack();
frame.setVisible(true);
}
});
}
static class ALittleSomethingPanel extends JPanel {
private JLabel aLittleSomethingLabel = new JLabel("A Little Something");
ALittleSomethingPanel() {
add(aLittleSomethingLabel);
aLittleSomethingLabel.setFont(aLittleSomethingLabel.getFont().deriveFont(42f));
}
}
static class ALittleSomethingUI extends LayerUI<JComponent> {
@Override
public void paint(Graphics g, JComponent c) {
Graphics2D g2 = (Graphics2D) g.create();
super.paint(g2, c);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int height = c.getHeight();
int width = c.getWidth();
Shape circle = new Ellipse2D.Double(5, 5, width - 10, height - 10);
g2.setPaint(new GradientPaint(15, 0, new Color(90, 97, 105), 15, 30, new Color(132, 142, 152)));
g2.setStroke(new BasicStroke(5));
g2.draw(circle);
g2.dispose();
}
}
}