用Java Swing製作歡迎畫面

來源:互聯網
上載者:User

幾乎所有時髦的應用都有一個歡迎畫面。歡迎畫面既是宣傳產品的方法之一,而且在長時間的應用啟動過程中,歡迎畫面還用來表示應用正在準備過程中。

下面是一個最簡單的歡迎畫面實現:

class SplashWindow1 extends JWindow
{
  public SplashWindow1(String filename, Frame f)
  {
   super(f);
   JLabel l = new JLabel(new ImageIcon(filename));
   getContentPane().add(l, BorderLayout.CENTER);
   pack();
   Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
   Dimension labelSize = l.getPreferredSize();
   setLocation(screenSize.width/2 - (labelSize.width/2),
   screenSize.height/2 - (labelSize.height/2));
   setVisible(true);
   screenSize = null;
   labelSize = null;
  }
}

SplashWindow1類從Swing的JWindow派生。JWindow是一個容器,它沒有其他視窗所具有的各種視窗元素,如標題條、視窗管理按鈕,甚至連反白的邊框也沒有。因此,JWindow對於製作歡迎畫面來說是非常合適的。上面的代碼假定圖形檔案在目前的目錄。圖形通過ImageIcon裝入記憶體,然後它就被放到了JWindow的中心。接著,視窗被pack(),這使得Swing把視窗調整到適當的大小,最後視窗被移到了螢幕的中心。

如果我們運行上面的程式,可以發現雖然歡迎畫面確實出現在螢幕中央,但遺憾的,它卻不會關閉!要關閉歡迎畫面,我們需要加入更多的代碼:

class SplashWindow2 extends JWindow
{
  public SplashWindow2(String filename, Frame f)
  {
   super(f);
   JLabel l = new JLabel(new ImageIcon(filename));
   getContentPane().add(l, BorderLayout.CENTER);
   pack();
   Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
   Dimension labelSize = l.getPreferredSize();
   setLocation(screenSize.width/2 - (labelSize.width/2),
   screenSize.height/2 - (labelSize.height/2));
   addMouseListener(new MouseAdapter()
   {  
    public void mousePressed(MouseEvent e)
    {
     setVisible(false);
     dispose();
    }
   });
   setVisible(true);
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.