在 Java Swing 中创建形状窗口
借助 JDK 7,我们可以非常轻松地使用 swing 创建形状窗口。以下是要制作形状窗口的步骤。
向框架添加组件监听器并覆盖 componentResized() 来更改框架的形状。无论何时更改窗口大小,此方法都会正确地重新计算框架的形状。
frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { frame.setShape(new RoundRectangle2D.Double(0,0,frame.getWidth(), frame.getHeight(), 20, 20)); } });
示例
请参见以下形状窗口示例。
import java.awt.Color; import java.awt.GridBagLayout; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.RoundRectangle2D; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class Tester { public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); // Create the GUI on the event-dispatching thread SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createWindow(); } }); } private static void createWindow() { JFrame frame = new JFrame("Rounded Shaped Window"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setVisible(true); } private static void createUI(final JFrame frame) { frame.setLayout(new GridBagLayout()); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.add(new JButton("Hello World")); frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { frame.setShape(new RoundRectangle2D.Double(0,0,frame.getWidth(), frame.getHeight(), 20, 20)); } }); } }
输出
广告