问题描述
如何在未装饰的jframe中添加阴影?
How do you add a shadow to a undecorated jframe?
根据我在网上找到的内容,您也许可以将jframe添加到另一个黑色半透明窗口中以产生阴影效果.或以某种方式将这样的内容应用于JFrame:
From what I found online, you might be able to add the jframe to another black translucent window to give a shadow effect.Or somehow apply something like this to a JFrame:
Border loweredBorder = new EtchedBorder(EtchedBorder.LOWERED);
setBorder(loweredBorder);
无论哪种方式,我只想知道最好的方法,或者是一种完全不同的方式来获得相同的效果,例如从另一个类而不是从jframe扩展.我是Java的新手,所以我可能走错了方向,因此请接受任何建议.
Either way I just want to know the best method or maybe a completely different way of getting the same effect like extending from another class and not jframe.I'm new to Java so I might be going down the wrong direction so any advice is appreciated.
推荐答案
基本上,您需要制作一系列图层.
Basically, you need to make a series of layers.
-
JFrame
-
ShadowPanel
- 和内容...
JFrame
ShadowPanel
- and content...
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class ShadowWindow {
public static void main(String[] args) {
new ShadowWindow();
}
public ShadowWindow() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ShadowPane());
JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Look ma, no hands"));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ShadowPane extends JPanel {
public ShadowPane() {
setLayout(new BorderLayout());
setOpaque(false);
setBackground(Color.BLACK);
setBorder(new EmptyBorder(0, 0, 10, 10));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.fillRect(10, 10, getWidth(), getHeight());
g2d.dispose();
}
}
}
这篇关于未修饰的JFrame阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!