电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Java-JFrame窗體美化方式

瀏覽:66日期:2022-08-21 09:18:56

JFrame默認(rèn)的窗體比較土,可以通過一定的美化,讓窗體表現(xiàn)的比較漂亮,具體要根據(jù)設(shè)計(jì)的設(shè)計(jì)圖進(jìn)行美化;

JFrame美化的大致思路:先將JFrame去除默認(rèn)美化效果,實(shí)現(xiàn)JWindow效果,然后再JWindow基礎(chǔ)上對(duì)窗體的各項(xiàng)內(nèi)容自定義設(shè)置與美化,大多用到插入背景圖片、添加各種鼠標(biāo)事件、彈窗與輸入框等圓角等各種美化;

下面是一個(gè)登錄窗體的美化代碼,以后再有對(duì)窗體美化的可以參照一下代碼進(jìn)行美化:

1、Login實(shí)體類代碼:

package com; import java.awt.Color;import java.awt.EventQueue;import java.awt.Font;import java.awt.Image;import java.awt.geom.RoundRectangle2D;import java.io.File; import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLayeredPane;import javax.swing.JPanel;import javax.swing.JRootPane;import javax.swing.JLabel; import com.alibaba.fastjson.JSON;import com.model.Message;import com.model.User;import com.sun.awt.AWTUtilities;import com.util.FileUtils;import com.util.MyButton;import com.util.MyLineBorder;import com.util.VerifyCodeUtils; import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JTextField;import javax.swing.border.MatteBorder;import javax.swing.JPasswordField;import java.awt.event.FocusAdapter;import java.awt.event.FocusEvent;/** * 用戶登錄窗體(按照設(shè)計(jì)圖片效果制作) * @author admin * */public class Login1{ private JFrame frame;//窗體 private JTextField userNameField;//用戶名輸入框 private JPasswordField passwordField;//密碼輸入框 private JTextField verifyCodeField;//驗(yàn)證碼輸入框 private String verifyCode;//驗(yàn)證碼圖片中的驗(yàn)證碼值 /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() {try { Login1 window = new Login1(); window.frame.setVisible(true);} catch (Exception e) { e.printStackTrace();} } }); } /** * Create the application. */ public Login1() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { //將存儲(chǔ)驗(yàn)證碼文件夾下的所有驗(yàn)證碼圖片刪除 FileUtils.deleteAllFiles('./verifyCodeImg'); //自定義圓角輸入框邊界線 MyLineBorder myLineBorder = new MyLineBorder(new Color(192, 192, 192), 1 , true); //只顯示輸入框的下邊框 MatteBorder bottomBorder = new MatteBorder(0, 0, 1, 0, new Color(192, 192, 192)); //設(shè)置JFrame禁用本地外觀,使用下面自定義設(shè)置的外觀; JFrame.setDefaultLookAndFeelDecorated(true); frame = new JFrame(); frame.setBounds(0, 0, 300, 490); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); /** * 對(duì)窗體進(jìn)行基本設(shè)置 */ //設(shè)置窗體在計(jì)算機(jī)窗口的中心部位顯示 frame.setLocationRelativeTo(frame.getOwner()); // 去掉窗口的裝飾 frame.setUndecorated(true); //采用指定的窗口裝飾風(fēng)格 frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE); //設(shè)置窗體圓角,最后兩個(gè)參數(shù)分別為圓角的寬度、高度數(shù)值,一般這兩個(gè)數(shù)值都是一樣的 AWTUtilities.setWindowShape(frame,new RoundRectangle2D.Double(0.0D, 0.0D, frame.getWidth(), frame.getHeight(), 20.0D, 20.0D)); //設(shè)置背景顏色,記住一定要修改frame.getContentPane()的顏色,因?yàn)槲覀兛吹降亩际沁@個(gè)的顏色而并不是frame的顏色 frame.getContentPane().setBackground(Color.white); /** * 插入頂部非凡汽車背景圖片 */ //創(chuàng)建具有分層的JLayeredPane JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setBounds(0, -5, 300, 200); frame.getContentPane().add(layeredPane); // 創(chuàng)建圖片對(duì)象 ImageIcon img = new ImageIcon(Login1.class.getResource('/images/dingbu.jpg')); //設(shè)置圖片在窗體中顯示的寬度、高度 img.setImage(img.getImage().getScaledInstance(300, 200,Image.SCALE_DEFAULT)); JPanel panel = new JPanel(); panel.setBounds(0, -5, 300, 200); layeredPane.add(panel, JLayeredPane.DEFAULT_LAYER); JLabel lblNewLabel = new JLabel(''); panel.add(lblNewLabel); lblNewLabel.setIcon(img); /** * 插入窗體關(guān)閉的背景圖片及功能 */ // 創(chuàng)建圖片對(duì)象 ImageIcon closeImg = new ImageIcon(Login1.class.getResource('/images/close.png')); //設(shè)置圖片在窗體中顯示的寬度、高度 closeImg.setImage(closeImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT)); JPanel closePanel = new JPanel(); closePanel.setBounds(269, -5, 31, 31); layeredPane.add(closePanel,JLayeredPane.MODAL_LAYER); JLabel closeLabel = new JLabel(''); closePanel.add(closeLabel); closeLabel.setIcon(closeImg); closeLabel.addMouseListener(new MouseAdapter() { //鼠標(biāo)點(diǎn)擊關(guān)閉圖片,實(shí)現(xiàn)關(guān)閉窗體的功能 @Override public void mouseClicked(MouseEvent e) {//dispose(); System.exit(0);//使用dispose();也可以關(guān)閉只是不是真正的關(guān)閉 } //鼠標(biāo)進(jìn)入,換關(guān)閉的背景圖片 @Override public void mouseEntered(MouseEvent e) {// 創(chuàng)建圖片對(duì)象ImageIcon closeImg1 = new ImageIcon(Login1.class.getResource('/images/mouse_close.png'));//設(shè)置圖片在窗體中顯示的寬度、高度closeImg1.setImage(closeImg1.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));closeLabel.setIcon(closeImg1); } //鼠標(biāo)離開,換關(guān)閉的背景圖片 @Override public void mouseExited(MouseEvent e) {// 創(chuàng)建圖片對(duì)象ImageIcon closeImg = new ImageIcon(Login1.class.getResource('/images/close.png'));//設(shè)置圖片在窗體中顯示的寬度、高度closeImg.setImage(closeImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));closeLabel.setIcon(closeImg); } }); /** * 插入窗體最小化的背景圖片及功能 */ // 創(chuàng)建圖片對(duì)象 ImageIcon minImg = new ImageIcon(Login1.class.getResource('/images/min.png')); //設(shè)置圖片在窗體中顯示的寬度、高度 minImg.setImage(minImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT)); JPanel minPanel = new JPanel(); minPanel.setBounds(237, -5, 31, 31); layeredPane.add(minPanel,JLayeredPane.MODAL_LAYER); JLabel minLabel = new JLabel(''); minLabel.addMouseListener(new MouseAdapter() { //鼠標(biāo)點(diǎn)擊最小化圖片,實(shí)現(xiàn)最小化窗體的功能 @Override public void mouseClicked(MouseEvent e) {frame.setExtendedState(JFrame.ICONIFIED);//最小化窗體 } //鼠標(biāo)進(jìn)入,換最小化的背景圖片 @Override public void mouseEntered(MouseEvent e) {// 創(chuàng)建圖片對(duì)象ImageIcon minImg1 = new ImageIcon(Login1.class.getResource('/images/mouse_min.png'));//設(shè)置圖片在窗體中顯示的寬度、高度minImg1.setImage(minImg1.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));minLabel.setIcon(minImg1); } //鼠標(biāo)離開,換最小化的背景圖片 @Override public void mouseExited(MouseEvent e) {// 創(chuàng)建圖片對(duì)象ImageIcon minImg = new ImageIcon(Login1.class.getResource('/images/min.png'));//設(shè)置圖片在窗體中顯示的寬度、高度minImg.setImage(minImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));minLabel.setIcon(minImg); } }); minPanel.add(minLabel); minLabel.setIcon(minImg); /** * 插入用戶名輸入框前面的圖片 */ // 創(chuàng)建圖片對(duì)象 ImageIcon userNameImg = new ImageIcon(Login1.class.getResource('/images/user_name.png')); //設(shè)置圖片在窗體中顯示的寬度、高度 userNameImg.setImage(userNameImg.getImage().getScaledInstance(40, 40,Image.SCALE_DEFAULT)); JLabel userNameLabel = new JLabel(''); userNameLabel.setBounds(0, 220, 40, 40); userNameLabel.setIcon(userNameImg); //默認(rèn)獲取光標(biāo) userNameLabel.setFocusable(true); frame.getContentPane().add(userNameLabel); /** * 添加圓角的用戶名輸入框 */ userNameField = new JTextField(); userNameField.setBounds(50, 220, 235, 50); userNameField.setBorder(bottomBorder); userNameField.setText(' 用戶名'); userNameField.setFont(new Font('微軟雅黑', 0, 14)); userNameField.setForeground(Color.GRAY);//默認(rèn)設(shè)置輸入框中的文字顏色為灰色 userNameField.addFocusListener(new FocusAdapter() { //獲取光標(biāo)事件 @Override public void focusGained(FocusEvent e) {//獲取焦點(diǎn)時(shí),輸入框中內(nèi)容是“用戶名”,那么去掉輸入框中顯示的內(nèi)容;if('用戶名'.equals((userNameField.getText().trim()))){ userNameField.setText(''); userNameField.setForeground(Color.black);//設(shè)置顏色為黑色} } //失去光標(biāo)事件 @Override public void focusLost(FocusEvent e) {//失去焦點(diǎn)時(shí),如果輸入框中去掉空格后的字符串為空串則顯示用戶名if(''.equals((userNameField.getText().trim()))){ userNameField.setText(' 用戶名'); userNameField.setFont(new Font('微軟雅黑', 0, 14)); userNameField.setForeground(Color.GRAY);//默認(rèn)設(shè)置輸入框中的文字顏色為灰色} } }); frame.getContentPane().add(userNameField); userNameField.setColumns(10); /** * 插入密碼輸入框前面的圖片 */ // 創(chuàng)建圖片對(duì)象 ImageIcon passwordImg = new ImageIcon(Login1.class.getResource('/images/password.png')); //設(shè)置圖片在窗體中顯示的寬度、高度 passwordImg.setImage(passwordImg.getImage().getScaledInstance(40, 40,Image.SCALE_DEFAULT)); JLabel passwordLabel = new JLabel(''); passwordLabel.setBounds(0, 280, 40, 40); passwordLabel.setIcon(passwordImg); frame.getContentPane().add(passwordLabel); /** * 添加圓角的密碼輸入框 */ passwordField = new JPasswordField(); passwordField.setBounds(50, 280, 235, 50); passwordField.setBorder(bottomBorder); passwordField.setText(' 密碼'); passwordField.setFont(new Font('微軟雅黑', 0, 14)); passwordField.setForeground(Color.GRAY);//默認(rèn)設(shè)置輸入框中的文字顏色為灰色 passwordField.setEchoChar((char)0);//顯示密碼輸入框中內(nèi)容 passwordField.addFocusListener(new FocusAdapter() { //獲取光標(biāo)事件 @Override public void focusGained(FocusEvent e) {//獲取焦點(diǎn)時(shí),輸入框中內(nèi)容是“用戶名”,那么去掉輸入框中顯示的內(nèi)容;if('密碼'.equals((passwordField.getText().trim()))){ passwordField.setText(''); passwordField.setEchoChar(’*’);//顯示密碼輸入框中內(nèi)容 passwordField.setForeground(Color.black);//設(shè)置顏色為黑色} } //失去光標(biāo)事件 @Override public void focusLost(FocusEvent e) {//失去焦點(diǎn)時(shí),如果輸入框中去掉空格后的字符串為空串則顯示用戶名if(''.equals((passwordField.getText().trim()))){ passwordField.setText(' 密碼'); passwordField.setFont(new Font('微軟雅黑', 0, 14)); passwordField.setForeground(Color.GRAY);//默認(rèn)設(shè)置輸入框中的文字顏色為灰色 passwordField.setEchoChar((char)0);//顯示密碼輸入框中內(nèi)容} } }); frame.getContentPane().add(passwordField); /** * 插入驗(yàn)證碼輸入框前面的圖片 */ // 創(chuàng)建圖片對(duì)象 ImageIcon verifyCodeImg = new ImageIcon(Login1.class.getResource('/images/verify_code.png')); //設(shè)置圖片在窗體中顯示的寬度、高度 verifyCodeImg.setImage(verifyCodeImg.getImage().getScaledInstance(40, 40,Image.SCALE_DEFAULT)); JLabel verifyCodeLabel = new JLabel(''); verifyCodeLabel.setBounds(0, 340, 40, 40); verifyCodeLabel.setIcon(verifyCodeImg); frame.getContentPane().add(verifyCodeLabel); /** * 添加圓角的驗(yàn)證碼輸入框 */ verifyCodeField = new JTextField(); verifyCodeField.setBounds(50, 340, 135, 50); verifyCodeField.setBorder(bottomBorder); verifyCodeField.setText(' 驗(yàn)證碼'); verifyCodeField.setFont(new Font('微軟雅黑', 0, 14)); verifyCodeField.setForeground(Color.GRAY);//默認(rèn)設(shè)置輸入框中的文字顏色為灰色 verifyCodeField.addFocusListener(new FocusAdapter() { //獲取光標(biāo)事件 @Override public void focusGained(FocusEvent e) {//獲取焦點(diǎn)時(shí),輸入框中內(nèi)容是“用戶名”,那么去掉輸入框中顯示的內(nèi)容;if('驗(yàn)證碼'.equals((verifyCodeField.getText().trim()))){ verifyCodeField.setText(''); verifyCodeField.setForeground(Color.black);//設(shè)置顏色為黑色} } //失去光標(biāo)事件 @Override public void focusLost(FocusEvent e) {//失去焦點(diǎn)時(shí),如果輸入框中去掉空格后的字符串為空串則顯示用戶名if(''.equals((verifyCodeField.getText().trim()))){ verifyCodeField.setText(' 驗(yàn)證碼'); verifyCodeField.setFont(new Font('微軟雅黑', 0, 14)); verifyCodeField.setForeground(Color.GRAY);//默認(rèn)設(shè)置輸入框中的文字顏色為灰色} } }); frame.getContentPane().add(verifyCodeField); verifyCodeField.setColumns(10); /** * 添加驗(yàn)證碼圖片 */ JLabel verifyCodeImgLabel = new JLabel(''); verifyCodeImgLabel.setBounds(190, 340, 95, 50); verifyCodeImgLabel.setBorder(myLineBorder); frame.getContentPane().add(verifyCodeImgLabel); //生成一張驗(yàn)證碼圖片 verifyCode = VerifyCodeUtils.createOneCodeImage(); //將剛生成的驗(yàn)證碼圖片顯示在窗體中去 ImageIcon verifyCodeSourceImg = new ImageIcon('./verifyCodeImg/'+verifyCode+'.jpg');// 創(chuàng)建圖片對(duì)象 //設(shè)置圖片在窗體中顯示的寬度、高度 verifyCodeSourceImg.setImage(verifyCodeSourceImg.getImage().getScaledInstance(95, 50,Image.SCALE_DEFAULT)); verifyCodeImgLabel.setIcon(verifyCodeSourceImg); //點(diǎn)擊驗(yàn)證碼圖片,換一個(gè)新的驗(yàn)證碼圖片 verifyCodeImgLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) {//刪除上一次的驗(yàn)證碼圖片F(xiàn)ile file = new File('./src/verifyCodeImg/'+verifyCode+'.jpg');if(file.exists()){ file.delete();}//生成一張新的驗(yàn)證碼圖片verifyCode = VerifyCodeUtils.createOneCodeImage();ImageIcon verifyCodeSourceImg1 = new ImageIcon('./verifyCodeImg/'+verifyCode+'.jpg');verifyCodeSourceImg1.setImage(verifyCodeSourceImg1.getImage().getScaledInstance(95, 50,Image.SCALE_DEFAULT));verifyCodeImgLabel.setIcon(verifyCodeSourceImg1); } }); /** * 添加提示性信息的JLabel */ JLabel reminderMessage = new JLabel('',JLabel.CENTER); reminderMessage.setBounds(15, 395, 270, 20); reminderMessage.setForeground(Color.red); reminderMessage.setFont(new Font('微軟雅黑', 0, 12)); frame.getContentPane().add(reminderMessage); /** * 添加圓角的提交按鈕 */ MyButton myButton = new MyButton('安全登錄', 0); myButton.setBounds(15, 420, 270, 50); frame.getContentPane().add(myButton); //設(shè)置窗體可見 frame.setVisible(true); }}

2、工具類FileUtils代碼:

package com.util; import java.io.File; /** * 對(duì)文件操作的工具類 * @author admin * */public class FileUtils { /** * 刪除指定文件夾下的所有文件,此文件夾內(nèi)只有文件,沒有任何文件夾 */ public static Boolean deleteAllFiles(String filePath){ Boolean result = false; File file = new File(filePath); File temp = null; if(file.exists()){ String [] tempList = file.list(); for (String string : tempList) {temp = new File(filePath+'/'+string);if(temp.isFile()){ temp.delete();} } tempList = file.list(); if(tempList.length==0){result = true; } } return result; } public static void main(String[] args) { Boolean result = FileUtils.deleteAllFiles('./verifyCodeImg'); System.out.println(result); } }

3、工具類MyButton代碼:

package com.util; import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.GradientPaint;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Insets;import java.awt.RenderingHints;import java.awt.Shape;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.geom.RoundRectangle2D;import javax.swing.JButton;import javax.swing.JFrame;/** * 自定義帶有圓角的按鈕工具類 * @author admin * */public class MyButton extends JButton { /* 決定圓角的弧度 */ public static int radius = 4; public static Color COLOR1, COLOR2; public static int pink = 3, ashen = 2, sky = 1, stone = 0; /* 粉紅 */ public static Color pink1 = new Color(39, 121, 181); public static Color pink2 = new Color(39, 121, 181); /* 灰白 */ public static Color ashen1 = new Color(39, 121, 181); public static Color ashen2 = new Color(39, 121, 181); /* 深寶石藍(lán) */ public static Color stone1 = new Color(39, 121, 181); public static Color stone2 = new Color(39, 121, 181); /* 淡天藍(lán)色 */ public static Color sky1 = new Color(39, 121, 181); public static Color sky2 = new Color(39, 121, 181); /* 光標(biāo)進(jìn)入按鈕判斷 */ private boolean hover; public MyButton() { this('', stone); } public MyButton(String name) { this(name, stone); } public MyButton(String name, int style) { super.setText(name); if (style == pink) { COLOR1 = pink1; COLOR2 = pink2; } if (style == ashen) { COLOR1 = ashen1; COLOR2 = ashen2; } if (style == stone) { COLOR1 = stone1; COLOR2 = stone2; } if (style == sky) { COLOR1 = sky1; COLOR2 = sky2; } paintcolor(COLOR1, COLOR2); } private void paintcolor(Color COLOR1, Color COLOR2) { setMargin(new Insets(0, 0, 0, 0)); setFont(new Font('微軟雅黑', 0, 14)); setBorderPainted(false); setForeground(Color.white); setFocusPainted(false); setContentAreaFilled(false); } @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); int height = getHeight(); int with = getWidth(); float tran = 0.9F; /*if (!hover) { 鼠標(biāo)離開/進(jìn)入時(shí)的透明度改變量 tran = 0.6F; }*/ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); /* GradientPaint是顏色漸變類 */ GradientPaint p1; GradientPaint p2; if (getModel().isPressed()) { p1 = new GradientPaint(0, 0, new Color(0, 0, 0), 0, height, new Color(100, 100, 100), true); p2 = new GradientPaint(0, 1, new Color(0, 0, 0, 50), 0, height, new Color(255, 255, 255, 100), true); } else { p1 = new GradientPaint(0, 0, new Color(100, 100, 100), 0, height, new Color(0, 0, 0), true); p2 = new GradientPaint(0, 1, new Color(255, 255, 255, 100), 0, height, new Color(0, 0, 0, 50), true); } g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, tran)); RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, with - 1, height - 1, radius, radius); // 最后兩個(gè)參數(shù)數(shù)值越大,按鈕越圓,以下同理 Shape clip = g2d.getClip(); g2d.clip(r2d); GradientPaint gp = new GradientPaint(0.0F, 0.0F, COLOR1, 0.0F, height / 2, COLOR2, true); g2d.setPaint(gp); g2d.fillRect(0, 0, with, height); g2d.setClip(clip); g2d.setPaint(p1); g2d.drawRoundRect(0, 0, with - 3, height - 3, radius, radius); g2d.setPaint(p2); g2d.drawRoundRect(1, 1, with - 3, height - 3, radius, radius); g2d.dispose(); super.paintComponent(g); } public static void main(String args[]) { JFrame frm = new JFrame(); MyButton but = new MyButton('圓角JButton', 0); frm.setLayout(null); frm.setBounds(800, 400, 500, 200); but.setBounds(30, 30, 200, 50); frm.add(but); frm.setDefaultCloseOperation(3); frm.setVisible(true); }}

4、工具類MyLineBorder代碼:

package com.util; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.border.LineBorder; /** * 為創(chuàng)建圓角輸入框自定義邊框線條工具類 * @author admin * */public class MyLineBorder extends LineBorder{ private static final long serialVersionUID = 1L; public MyLineBorder(Color color, int thickness, boolean roundedCorners) { super(color, thickness, roundedCorners); } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color oldColor = g.getColor(); Graphics2D g2 = (Graphics2D)g; int i; g2.setRenderingHints(rh); g2.setColor(lineColor); for(i = 0; i < thickness; i++) { if(!roundedCorners)g2.drawRect(x+i, y+i, width-i-i-1, height-i-i-1); elseg2.drawRoundRect(x+i, y+i, width-i-i-1, height-i-i-1, 10, 10); //就是這一句 ,后兩個(gè)參數(shù)控制圓角的大小 } g2.setColor(oldColor); } }

5、工具類VerifyCodeUtils代碼:

package com.util; import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Arrays;import java.util.Random; import javax.imageio.ImageIO;/** * 生成驗(yàn)證碼圖片的工具類 * @author admin * */public class VerifyCodeUtils { // 使用到Algerian字體,系統(tǒng)里沒有的話需要安裝字體,字體只顯示大寫,去掉了1,0,i,o幾個(gè)容易混淆的字符 public static final String VERIFY_CODES = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; private static Random random = new Random(); /** * 使用系統(tǒng)默認(rèn)字符源生成驗(yàn)證碼 * * @param verifySize * 驗(yàn)證碼長(zhǎng)度 * @return */ public static String generateVerifyCode(int verifySize) { return generateVerifyCode(verifySize, VERIFY_CODES); } /** * 使用指定源生成驗(yàn)證碼 * * @param verifySize * 驗(yàn)證碼長(zhǎng)度 * @param sources * 驗(yàn)證碼字符源 * @return */ public static String generateVerifyCode(int verifySize, String sources) { if (sources == null || sources.length() == 0) { sources = VERIFY_CODES; } int codesLen = sources.length(); Random rand = new Random(System.currentTimeMillis()); StringBuilder verifyCode = new StringBuilder(verifySize); for (int i = 0; i < verifySize; i++) { verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1))); } return verifyCode.toString(); } /** * 生成隨機(jī)驗(yàn)證碼文件,并返回驗(yàn)證碼值 * * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException { String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, outputFile, verifyCode); return verifyCode; } /** * 輸出隨機(jī)驗(yàn)證碼圖片流,并返回驗(yàn)證碼值 * * @param w * @param h * @param os * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException { String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, os, verifyCode); return verifyCode; } /** * 生成指定驗(yàn)證碼圖像文件 * * @param w * @param h * @param outputFile * @param code * @throws IOException */ public static void outputImage(int w, int h, File outputFile, String code) throws IOException { if (outputFile == null) { return; } File dir = outputFile.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try { outputFile.createNewFile(); FileOutputStream fos = new FileOutputStream(outputFile); outputImage(w, h, fos, code); fos.close(); } catch (IOException e) { throw e; } } /** * 輸出指定驗(yàn)證碼圖片流 * * @param w * @param h * @param os * @param code * @throws IOException */ public static void outputImage(int w, int h, OutputStream os, String code) throws IOException { int verifySize = code.length(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Random rand = new Random(); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color[] colors = new Color[5]; Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,Color.ORANGE, Color.PINK, Color.YELLOW }; float[] fractions = new float[colors.length]; for (int i = 0; i < colors.length; i++) { colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; fractions[i] = rand.nextFloat(); } Arrays.sort(fractions); g2.setColor(Color.GRAY);// 設(shè)置邊框色 g2.fillRect(0, 0, w, h); Color c = getRandColor(200, 250); g2.setColor(c);// 設(shè)置背景色 g2.fillRect(0, 2, w, h - 4); // 繪制干擾線 Random random = new Random(); g2.setColor(getRandColor(160, 200));// 設(shè)置線條的顏色 for (int i = 0; i < 20; i++) { int x = random.nextInt(w - 1); int y = random.nextInt(h - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g2.drawLine(x, y, x + xl + 40, y + yl + 20); } // 添加噪點(diǎn) float yawpRate = 0.05f;// 噪聲率 int area = (int) (yawpRate * w * h); for (int i = 0; i < area; i++) { int x = random.nextInt(w); int y = random.nextInt(h); int rgb = getRandomIntColor(); image.setRGB(x, y, rgb); } shear(g2, w, h, c);// 使圖片扭曲 g2.setColor(getRandColor(100, 160)); int fontSize = h - 4; Font font = new Font('Algerian', Font.ITALIC, fontSize); g2.setFont(font); char[] chars = code.toCharArray(); for (int i = 0; i < verifySize; i++) { AffineTransform affine = new AffineTransform(); affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2); g2.setTransform(affine); g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10); } g2.dispose(); ImageIO.write(image, 'jpg', os); } private static Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private static int getRandomIntColor() { int[] rgb = getRandomRgb(); int color = 0; for (int c : rgb) { color = color << 8; color = color | c; } return color; } private static int[] getRandomRgb() { int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { rgb[i] = random.nextInt(255); } return rgb; } private static void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private static void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) {g.setColor(color);g.drawLine((int) d, i, 0, i);g.drawLine((int) d + w1, i, w1, i); } } } private static void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) {g.setColor(color);g.drawLine(i, (int) d, i, 0);g.drawLine(i, (int) d + h1, i, h1); } } } //生成一張驗(yàn)證碼圖片,并保存到項(xiàng)目的verifyCodeImg文件夾下 public static String createOneCodeImage(){ String imgName = ''; try { File dir = new File('./verifyCodeImg'); int w = 95, h = 50; String verifyCode = generateVerifyCode(4); File file = new File(dir, verifyCode + '.jpg'); outputImage(w, h, file, verifyCode); imgName = verifyCode; } catch (IOException e) { imgName = ''; e.printStackTrace(); }finally{ return imgName; } } public static void main(String[] args) throws IOException { String codeImage = VerifyCodeUtils.createOneCodeImage(); System.out.println(codeImage); }}

補(bǔ)充知識(shí):Java Swing概述: JFrame窗體和JDialog窗體

GUI(圖形用戶界面)為程序員提供圖形界面,它最初的設(shè)計(jì)目的死為了程序員構(gòu)建一個(gè)通用的GUI,使其能夠在所有的平臺(tái)上運(yùn)行,但是Java 1.0 中的基礎(chǔ)類AWT(抽象窗口工具箱)并沒有達(dá)到這個(gè)要求,于是Swing出現(xiàn)了,它是AWT組建的增強(qiáng)組建,但是它并不能完全替代AWT,這兩種組件需要同時(shí)出現(xiàn)在一個(gè)圖形用戶界面中。

Swing組件

原來的AWT組件來自java.awt包,當(dāng)含有AWT組件的java應(yīng)用程序在不同的平臺(tái)上執(zhí)行時(shí),每個(gè)平臺(tái)的GUI組件的顯示會(huì)有所不同,但是在不同的平臺(tái)運(yùn)行Swing開發(fā)的應(yīng)用程序時(shí),就可以統(tǒng)一GUI組件的顯示風(fēng)格,因?yàn)镾wing組件允許編程人員在跨平臺(tái)時(shí)指定統(tǒng)一的外觀和風(fēng)格。

Swing組件通常被稱為“輕量級(jí)組件”,因?yàn)樗耆蒵ava語言編寫,而Java時(shí)不依賴于操作系統(tǒng)的語言,它可在任何平臺(tái)上運(yùn)行;相反,依賴于本地平臺(tái)的組件稱為“重量級(jí) 組件”,如AWT組件就是依賴本地平臺(tái)的窗口系統(tǒng)來決定組件的功能、外觀和風(fēng)格。Swing組件具有以下特點(diǎn):

輕量級(jí)組件

可插入外觀組件

Swing包

為了有效的使用Swing組件,必須了解Swing包的層次結(jié)構(gòu)和繼承關(guān)系,其中比較重要的是Component類、Container類和JComponent類。其中這幾個(gè)類的繼承關(guān)系如下:

javax.swing.JComponent 繼承自:

javax.awt.Container類繼承自:

javax.awt.Component繼承自:

java.lang.Object類

在Swing組件中大多數(shù)GUI組件都是Component類的直接子類或者間接子類,JComponent類是Swing組件各種特性的存放位置,這些組件的特性包括設(shè)定組件邊界,GUI組件自動(dòng)滾動(dòng)等。

在Swing組件中最重要的是父類Container類,而Container類有兩個(gè)重要的子類,分別為java.awt.Window and java.awt.Frame, 除了以往的AWT類組件會(huì)繼承這兩個(gè)類之外,現(xiàn)在的Swing組件也擴(kuò)展了這兩個(gè)類。

常用窗體

窗體作為Swing應(yīng)用程序中的組件的承載體,處于非常重要的位置。Swing中常用的窗體包括JFrame和JDialog。

JFrame窗體

JFrame窗體是一個(gè)容器,它是Swing程序中各個(gè)組件的載體,可以將JFrame看作是承載著血Swing組件的容器。在開發(fā)應(yīng)用程序時(shí),可以通過繼承java.swing.JFrame類創(chuàng)建一個(gè)窗體。在這個(gè)窗體中添加組件,同時(shí)為組件設(shè)置事件。

由于該窗體繼承了JFrame類,所以它擁有“最大化”、“最小化”、和“關(guān)閉”等按鈕

下面將詳細(xì)講解JFrame窗體在java應(yīng)用程序中的使用方法。

JFrame在程序中的語法如下:

JFrame jf = new JFrame(title);

Container container = jf.getContentPane();

參數(shù)含義如下:

jf:JFrame類對(duì)象

container: Container類的對(duì)象,可以使用JFrame對(duì)象調(diào)用getContentPane()方法獲取。

Swing組件的窗體通常與組件和容器有關(guān),所以JFrame對(duì)象創(chuàng)建完成后,需要調(diào)用getContentPane() 方法將窗體轉(zhuǎn)換為容器,然后在容器中添加組件或者設(shè)置布局管理器。

通常這個(gè)容器用來包含和顯示組件。如果需要將組件添加至容器,可以使用來自Container類的add方法進(jìn)行設(shè)置。例如:

container.add(new Button('按鈕'));

在容器中添加組件后,也可以使用Container類的remove() 方法將這些組件從容器中刪除,例如:

container.remove(new Button('按鈕'));

下面的實(shí)例實(shí)現(xiàn)了JFrame對(duì)象創(chuàng)建一個(gè)窗體,并在其中添加一個(gè)組件。

package com.xsh; import java.awt.Color;import java.awt.Container; import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.SwingConstants;import javax.swing.WindowConstants; public class Example1 extends JFrame { //創(chuàng)建一個(gè)類繼承JFrame類 public void CreateJFrame(String title) { //定義一個(gè)CreateJFrame方法 JFrame jf = new JFrame(title); //實(shí)例化一個(gè)JFrame對(duì)象 Container container = jf.getContentPane(); //獲取一個(gè)容器 JLabel jl = new JLabel('這是一個(gè)JFrame窗體'); //創(chuàng)建一個(gè)JLabel標(biāo)簽 jl.setHorizontalAlignment(SwingConstants.CENTER); //將標(biāo)簽位置設(shè)置為居中 jl.setForeground(Color.white); //設(shè)置JLabel的顏色 container.add(jl); //將標(biāo)簽添加到容器中 container.setBackground(Color.RED); //設(shè)置容器背景顏色 jf.setVisible(true); //是窗體可視 jf.setSize(300, 150); //設(shè)置窗體大小 jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //設(shè)置窗體關(guān)閉方式 } public static void main(String[] args) { // TODO Auto-generated method stub new Example1().CreateJFrame('這是我創(chuàng)建的第一個(gè)JFrame窗體。'); //主方法中調(diào)用JFrame()方法 }}

其運(yùn)行結(jié)果如下:

Java-JFrame窗體美化方式

在上述例子中,Example1類繼承了JFrame類,在CreateJFrame()方法中,實(shí)例化了JFrame對(duì)象。JFrame類的常用構(gòu)造方法包括以下兩種形式:

public JFrame().

Public JFrame(String title).

JFrame類中的兩種構(gòu)造方法分別為無參的構(gòu)造方法和有參的構(gòu)造方法。

第一種形式的構(gòu)造方法可以創(chuàng)建一個(gè)初始不可見、沒有標(biāo)題的新窗體;

第二種形式的構(gòu)造方法在實(shí)例化該JFrame對(duì)象時(shí)可以創(chuàng)建一個(gè)不可見但是具有標(biāo)題的窗體。

可以使用JFrame對(duì)象調(diào)用show()方法使窗體可見,但是該方法已經(jīng)被系版本的JDK中的setVisible(true)方法取代。

同時(shí)可以使用setSize(int i, int j)方法設(shè)置窗體大小,其中x與y變量分別代表窗體的寬和高

創(chuàng)建窗體以后,需要給窗體一個(gè)關(guān)閉方式,可以調(diào)用setDefaultCloseOPeration()方法關(guān)閉窗體。Java為窗體關(guān)閉提供了多種方式,

常用的有以下四種;

DO_NOTHING_ON_CLOSE

DISPOSE_ON_CLOSE)

HIDE_ON_CLOSE

EXIT_ON_CLOSE

JDialog

JDialog窗體是Swing組件中的對(duì)話框,它繼承了AWT組件中java.awt.Dialog類。

JDialog窗體的功能是從另外一個(gè)窗體中彈出另外一個(gè)窗體,就像是在使用IE瀏覽器時(shí)彈出的確定對(duì)話框一樣。JDialog窗體實(shí)質(zhì)上就是另一種類型的窗體,它與JFrame窗體類似,在使用時(shí)也需要調(diào)用getCOntentPane()方法將窗體轉(zhuǎn)換成容器,然后在容器中 設(shè)置窗體的特性。

在應(yīng)用程序中創(chuàng)建JDialog窗體需要實(shí)例化JDialog類,通常使用以下幾個(gè)JDialog類的構(gòu)造方法。

public JDialog():創(chuàng)建一個(gè)沒有標(biāo)題和副窗體的對(duì)話框

public JDialog(Frame f):創(chuàng)建一個(gè)指定父窗體的對(duì)話框,但是對(duì)話框沒有標(biāo)題

public JDialog(Frame f, boolean model):創(chuàng)建一個(gè)指定類型的對(duì)話框,并指定父窗體,但該窗體沒有指定標(biāo)題。

public JDialog(Frame f, String title):創(chuàng)建一個(gè)指定標(biāo)題和父窗體的對(duì)話框

public JDialog(Frame f, String title, boolean model):創(chuàng)建一個(gè)指定標(biāo)題,父窗體和模式的對(duì)話框

下面來看一個(gè)實(shí)例:

package com.xsh; import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener; import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.SwingConstants;import javax.swing.WindowConstants; class MyDialog extends JDialog{ private static final long serialVersionUID = 1L; public MyDialog(MyFrame frame) { super(frame,'第一個(gè)JDialog窗體', true); //實(shí)例化一個(gè)JDialog類對(duì)象,指定對(duì)話框的父窗體、窗體標(biāo)題和類型 Container container = getContentPane(); //創(chuàng)建一個(gè)容器 container.add(new JLabel('這是一個(gè)JDialog對(duì)話框')); //在容器中添加標(biāo)簽 setBounds(100, 100, 200, 100); //設(shè)置容器的窗體大小,其中前兩個(gè)值是設(shè)置對(duì)話框的位置,后兩個(gè)值是設(shè)置對(duì)話框的大小 }} public class MyFrame extends JFrame { //創(chuàng)建新類,繼承自JFrame private static final long serialVersionUID = 1L; public static void main(String[] args) { // TODO Auto-generated method stub new MyFrame(); //實(shí)例化MyFrame對(duì)象 } public MyFrame() { Container container = getContentPane(); //創(chuàng)建一個(gè)容器 container.setLayout(null); JLabel jl = new JLabel('這是一個(gè)JFrame窗體'); //在窗體中設(shè)置標(biāo)簽 jl.setHorizontalAlignment(SwingConstants.CENTER); //將標(biāo)簽的文字至于標(biāo)簽中間的位置 container.add(jl); //將標(biāo)簽添加到容器中 JButton jb = new JButton('彈出對(duì)話框'); //定義一個(gè)按鈕 jb.setBounds(10, 30, 100, 20); //設(shè)置按鈕的大小 jb.addActionListener(new ActionListener() { //為按鈕添加點(diǎn)擊事件 @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub new MyDialog(MyFrame.this).setVisible(true); //使MyDialog窗體可見 //在點(diǎn)擊事件中,完成了對(duì)話框的創(chuàng)建 } }); container.add(jb); container.setBackground(Color.white); setSize(200,200); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setVisible(true); }}

在本實(shí)例中,為了使對(duì)話框父窗體彈出,定義了一個(gè)JFrame窗體,首先在該窗體中定義了一個(gè)按鈕,然后為此按鈕添加了一個(gè)點(diǎn)擊事件。在點(diǎn)擊事件中,我們使用了new MyJDialog().setVisible(true) 語句使對(duì)話框窗體可見,這樣就實(shí)現(xiàn)了單機(jī) 按鈕之后彈出 對(duì)話框的功能。

在MyDialog類中,由于它繼承了JDialog類,所以可以在構(gòu)造方法中使用super關(guān)鍵字調(diào)用JDialog構(gòu)造方法。

在這里我們使用了 piublic JDialog(Frame f, String title, boolean model); 這種形式的構(gòu)造方法,相應(yīng)的設(shè)置了自定義的JFrame窗體以及對(duì)話框的標(biāo)題和窗體類型。

以上這篇Java-JFrame窗體美化方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: EPK超声波测厚仪,德国EPK测厚仪维修-上海树信仪器仪表有限公司 | 实验室隔膜泵-无油防腐蚀隔膜泵-耐腐蚀隔膜真空泵-杭州景程仪器 电杆荷载挠度测试仪-电杆荷载位移-管桩测试仪-北京绿野创能机电设备有限公司 | 开云(中国)Kaiyun·官方网站 - 登录入口| 辐射色度计-字符亮度测试-反射式膜厚仪-苏州瑞格谱光电科技有限公司 | 广州网站建设_小程序开发_番禺网站建设_佛山网站建设_粤联网络 | 智慧物联网行业一站式解决方案提供商-北京东成基业 | 定制异形重型钢格栅板/钢格板_定做踏步板/排水沟盖板_钢格栅板批发厂家-河北圣墨金属制品有限公司 | 塑料造粒机「厂家直销」-莱州鑫瑞迪机械有限公司 | 开云(中国)Kaiyun·官方网站-登录入口 | 磁力抛光机_磁力研磨机_磁力去毛刺机-冠古设备厂家|维修|租赁【官网】 | 浇注料-高铝砖耐火砖-郑州凯瑞得窑炉耐火材料有限公司 | 周易算网-八字测算网 - 周易算网-宝宝起名取名测名字周易八字测算网 | 臻知网大型互动问答社区-你的问题将在这里得到解答!-无锡据风网络科技有限公司 | 小程序开发公司-小程序制作-微信小程序开发-小程序定制-咏熠软件 | 渣土车电机,太阳能跟踪器电机,蜗轮蜗杆减速电机厂家-淄博传强电机 | 实战IT培训机构_IT培训班选大学生IT技术培训中心_中公优就业 | 金联宇电缆总代理-金联宇集团-广东金联宇电缆实业有限公司 | 北京开业庆典策划-年会活动策划公司-舞龙舞狮团大鼓表演-北京盛乾龙狮鼓乐礼仪庆典策划公司 | 雷达液位计_超声波风速风向仪_雨量传感器_辐射传感器-山东风途物联网 | 桁架楼承板-钢筋桁架楼承板-江苏众力达钢筋楼承板厂 | 基业箱_环网柜_配电柜厂家_开关柜厂家_开关断路器-东莞基业电气设备有限公司 | ★济南领跃标识制作公司★济南标识制作,标牌制作,山东标识制作,济南标牌厂 | 祝融环境-地源热泵多恒系统高新技术企业,舒适生活环境缔造者! | 行吊_电动单梁起重机_双梁起重机_合肥起重机_厂家_合肥市神雕起重机械有限公司 | 薄壁轴承-等截面薄壁轴承生产厂家-洛阳薄壁精密轴承有限公司 | 急救箱-应急箱-急救包厂家-北京红立方医疗设备有限公司 | TTCMS自助建站_网站建设_自助建站_免费网站_免费建站_天天向上旗下品牌 | 招商帮-一站式网络营销服务|互联网整合营销|网络推广代运营|信息流推广|招商帮企业招商好帮手|搜索营销推广|短视视频营销推广 | 聚合氯化铝价格_聚合氯化铝厂家_pac絮凝剂-唐达净水官网 | 汽车整车综合环境舱_军标砂尘_盐雾试验室试验箱-无锡苏南试验设备有限公司 | 青岛侦探调查_青岛侦探事务所_青岛调查事务所_青岛婚外情取证-青岛狄仁杰国际侦探公司 | 全屋整木定制-橱柜,家具定制-四川峨眉山龙马木业有限公司 | 标准光源箱|对色灯箱|色差仪|光泽度仪|涂层测厚仪_HRC大品牌生产厂家 | 赛尔特智能移动阳光房-阳光房厂家-赛尔特建筑科技(广东)有限公司 | 双相钢_双相不锈钢_双相钢圆钢棒_双相不锈钢报价「海新双相钢」 双能x射线骨密度检测仪_dxa骨密度仪_双能x线骨密度仪_品牌厂家【品源医疗】 | 高清视频编码器,4K音视频编解码器,直播编码器,流媒体服务器,深圳海威视讯技术有限公司 | 注塑机-压铸机-塑料注塑机-卧式注塑机-高速注塑机-单缸注塑机厂家-广东联升精密智能装备科技有限公司 | 机器视觉检测系统-视觉检测系统-机器视觉系统-ccd检测系统-视觉控制器-视控一体机 -海克易邦 | 污水/卧式/潜水/钻井/矿用/大型/小型/泥浆泵,价格,参数,型号,厂家 - 安平县鼎千泵业制造厂 | 天津云仓-天津仓储物流-天津云仓一件代发-顺东云仓 | 水性绝缘漆_凡立水_绝缘漆树脂_环保绝缘漆-深圳维特利环保材料有限公司 |