确定 Java 中的打开 Frame 或窗口的时间
要确定在 Java 中打开窗口的时间,请使用 WindowListener,这是用于接收窗口事件的监听器接口。
WindowListener listener = new WindowAdapter() { public void windowOpened(WindowEvent evt) { Frame frame = (Frame) evt.getSource(); System.out.println("Opened "+frame.getTitle()); } };
如上所述,我们使用了 windowOpened() 方法,该方法在窗口被打开时被调用 −
public void windowOpened(WindowEvent evt) { Frame frame = (Frame) evt.getSource(); System.out.println("Opened "+frame.getTitle()); }
以下是一个示例,用于确定在 Java 中打开框架或窗口的时间 −
示例
package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; public class SwingDemo { public static void main(String args[]) throws BadLocationException { JFrame frame = new JFrame("Demo"); WindowListener listener = new WindowAdapter() { public void windowOpened(WindowEvent evt) { Frame frame = (Frame) evt.getSource(); System.out.println("Opened "+frame.getTitle()); } }; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = frame.getContentPane(); JTextPane pane = new JTextPane(); SimpleAttributeSet attributeSet = new SimpleAttributeSet(); StyleConstants.setItalic(attributeSet, true); StyleConstants.setForeground(attributeSet, Color.black); StyleConstants.setBackground(attributeSet, Color.orange); pane.setCharacterAttributes(attributeSet, true); pane.setText("We are learning Java and this is a demo text!"); JScrollPane scrollPane = new JScrollPane(pane); container.add(scrollPane, BorderLayout.CENTER); frame.setSize(550, 300); frame.addWindowListener(listener); frame.setVisible(true); } }
输出
广告