效果如下
完整源代码
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class BackgroundPanel extends JPanel {
/**
* 背景图片
*/
private Image image;
/**
* 构造方法
*/
public BackgroundPanel() {
super();
setOpaque(false);
setLayout(null);
}
/**
* 设置图片的方法
*/
public void setImage(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {// 重写绘制组件外观
if (image != null) {
g.drawImage(image, 0, 0, 400, 406, this);// 绘制图片与组件大小相同
}
super.paintComponent(g);// 执行超类方法
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.sun.awt.AWTUtilities;
public class DiamondFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DiamondFrame frame = new DiamondFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DiamondFrame() {
setAlwaysOnTop(true);
setUndecorated(true);// 去掉窗体修饰
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
do_this_mouseClicked(e);
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
do_this_windowOpened(e);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 100, 400, 406);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
BackgroundPanel backgroundPanel = new BackgroundPanel();
URL resource = getClass().getResource("photo1.png");
Image image = getToolkit().getImage(resource);
backgroundPanel.setImage(image);
contentPane.add(backgroundPanel, BorderLayout.CENTER);
}
@SuppressWarnings("restriction")
protected void do_this_windowOpened(WindowEvent e) {
int[] xPoints = { 0, 50, 350, 400, 200, 0 };// 定义各顶点的X坐标
int[] yPoints = { 200, 100, 100, 200, 400, 200 };// 定义各顶点的Y坐标
Polygon polygon = new Polygon(xPoints, yPoints, 6);// 创建多边形
AWTUtilities.setWindowShape(this, polygon);// 设置窗体形状
}
protected void do_this_mouseClicked(MouseEvent e) {
dispose();// 销毁窗体
}
}
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
该博文为原创文章,未经博主同意不得转载。
本文章博客地址:https://cplusplus.blog.csdn.net/article/details/130252548