如何改变Swing窗口的外观?

下面的示例展示了如何在基于Swing的应用程序中更改窗口的外观。

使用以下API -

  • UIManager.getCrossPlatformLookAndFeelClassName() - 获取Java的外观和感觉。
  • UIManager.setLookAndFeel() - 设置UI组件的外观。
  • JFrame.setDefaultLookAndFeelDecorated(true); - 改变框架的外观和感觉。

示例

package com.zaixian.swingdemo;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class SwingTester {
   public static void main(String[] args) {
      try {
         UIManager.setLookAndFeel(
         UIManager.getCrossPlatformLookAndFeelClassName());
      } catch (Exception e) { 
   }
      JFrame.setDefaultLookAndFeelDecorated(true);
      createWindow();   
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("如何改变Swing窗口的外观");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(JFrame frame){      
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       
      panel.add(new JLabel("Welcome to xuhuhu.com "));

      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

执行上面示例代码,得到以下结果:

改变Swing窗口的外观


上一篇: Swing框架和窗口示例 下一篇: Swing列表框示例