什么是祝酒词?以及如何使用JavaSwing创建它们? Toast消息是一种通过短弹出消息通知用户的快速方式,持续时间很短,然后消失。
null
Java Swing没有用于toast消息的内置类,但toast消息是一种流行且有效的方式,用于显示仅在短时间内显示的自动过期消息。因此,为了实现toast消息,我们必须手动构建一个能够创建toast消息的类。
在本文中,我们将讨论如何使用Java Swing组件在Java中手动创建toast消息。以下程序将创建一条持续时间很短的文本祝酒词,然后这些祝酒词将消失。
有关半透明窗口和框架的更多详细信息,请阅读以下文章,这将为您提供如何实现半透明和成型窗口的想法。 Java Swing | Java中的半透明形状窗口 JSwing |半透明成型窗户
下面的程序创建toast消息(这是一个选择性半透明的窗口)
// Java program that creates the toast message //(which is a selectively translucent JWindow) import java.awt.*; import javax.swing.*; import java.awt.event.*; class toast extends JFrame { //String of toast String s; // JWindow JWindow w; toast(String s, int x, int y) { w = new JWindow(); // make the background transparent w.setBackground( new Color( 0 , 0 , 0 , 0 )); // create a panel JPanel p = new JPanel() { public void paintComponent(Graphics g) { int wid = g.getFontMetrics().stringWidth(s); int hei = g.getFontMetrics().getHeight(); // draw the boundary of the toast and fill it g.setColor(Color.black); g.fillRect( 10 , 10 , wid + 30 , hei + 10 ); g.setColor(Color.black); g.drawRect( 10 , 10 , wid + 30 , hei + 10 ); // set the color of text g.setColor( new Color( 255 , 255 , 255 , 240 )); g.drawString(s, 25 , 27 ); int t = 250 ; // draw the shadow of the toast for ( int i = 0 ; i < 4 ; i++) { t -= 60 ; g.setColor( new Color( 0 , 0 , 0 , t)); g.drawRect( 10 - i, 10 - i, wid + 30 + i * 2 , hei + 10 + i * 2 ); } } }; w.add(p); w.setLocation(x, y); w.setSize( 300 , 100 ); } // function to pop up the toast void showtoast() { try { w.setOpacity( 1 ); w.setVisible( true ); // wait for some time Thread.sleep( 2000 ); // make the message disappear slowly for ( double d = 1.0 ; d > 0.2 ; d -= 0.1 ) { Thread.sleep( 100 ); w.setOpacity(( float )d); } // set the visibility to false w.setVisible( false ); } catch (Exception e) { System.out.println(e.getMessage()); } } } |
运行上述程序的驱动程序。
// Java Program to create a driver class to run // the toast class import javax.swing.*; import java.awt.*; import java.awt.event.*; class driver extends JFrame implements ActionListener { // create a frame static JFrame f; // textfield static JTextField tf; public static void main(String args[]) { // create the frame f = new JFrame( "toast" ); driver d = new driver(); // textfield tf = new JTextField( 16 ); // button Button b = new Button( "create" ); // add action listener b.addActionListener(d); // create a panel JPanel p = new JPanel(); p.add(tf); p.add(b); // add panel f.add(p); // setSize f.setSize( 500 , 500 ); f.show(); } // if button is pressed public void actionPerformed(ActionEvent e) { // create a toast message toast t = new toast(tf.getText(), 150 , 400 ); // call the method t.showtoast(); } } |
输出:
注意:此程序不会在联机IDE中运行。请使用最新版本java的脱机IDE。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END