使用JDK 7,我们可以很容易地使用秋千创建一个成形的窗口。以下是制作成型窗户所需的步骤。
将组件侦听器添加到框架,并覆盖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); //在事件调度线程上创建GUI- 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)); } }); } }
输出结果