在JFrame上添加背景图片

来源:互联网 发布:网络词boom是什么意思 编辑:程序博客网 时间:2024/05/21 06:59

//本程序用来在JFrame上添加背景图片,使程序更加人性化!,添加方法用到了一个JPanel的内部类,并可以更改按钮的背景图片

package GUITest;/*@功能:本程序用主要就是在JFrame上添加背景,原理很简单,声明一个继承于Jpanel的内部类, *@在顶层容器JFrame上添加一个JPanel,然后设置Jpanel布局方式为null,并根据自己的需要在panel上添加相应的组件 *@Date:2014-5-10 最后修改 *@Author:何龙     *@QQ:471628912 */import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextField;import javax.swing.JWindow;public class LoginFrame extends JFrame {private JLabel label1, label2;private JTextField userName;// 用户名private JPasswordField password;// 密码输入框private JButton button1, button2;public LoginFrame() {getContentPane().setLayout(new BorderLayout(0, 0));JPanel panel = new ImagePanel();getContentPane().add(panel);// 设置panel的布局方式为nullpanel.setLayout(null);// 添加两个“用户名”“密码”的label,通过字体的大小更改label的大小label1 = new JLabel("用户名");label1.setFont(new Font("宋体", Font.BOLD, 26));label1.setForeground(Color.yellow);label1.setBounds(475, 350, 100, 50);label2 = new JLabel("密   码");label2.setFont(new Font("宋体", Font.BOLD, 26));label2.setForeground(Color.yellow);label2.setBounds(475, 430, 100, 50);// 添加两个输入框,用于输入用户名和密码。用户名用JTextFied,密码用JPasswordFielduserName = new JTextField(10);userName.setBounds(575, 350, 200, 50);userName.setFont(new Font("宋体", Font.BOLD, 20));userName.setColumns(15);password = new JPasswordField(10);password.setBounds(575, 430, 200, 50);password.setFont(new Font("宋体", Font.BOLD, 30));password.setColumns(15);// char c = '#';// password.setEchoChar(c);// 添加两个按钮,用于显示登录和注销功能!!button1 = new JButton("登陆");button1.setFont(new Font("宋体", Font.BOLD, 26));button1.setForeground(Color.black);button1.setBounds(475, 530, 100, 50);// 可以通过下面的语句更改button的按钮背景,可以用一张艺术字图片更改按钮上的图标,使按钮显得漂亮// button1.setIcon(new ImageIcon("src/pic/2.jpg"));button2 = new JButton("注销");button2.setFont(new Font("宋体", Font.BOLD, 26));button2.setForeground(Color.black);button2.setBounds(675, 530, 100, 50);// 添加所需组件panel.add(label1);panel.add(userName);panel.add(label2);panel.add(password);panel.add(button1);panel.add(button2);}public static void main(String args[]) {// new一个新的窗口,窗口是在构造器中生成的,而JApplet可以在init()方法里初始化,注意这两者的区别LoginFrame frame = new LoginFrame();frame.setSize(900, 700);// 窗体大下frame.setLocation(100, 100);// 窗口初始位置frame.setResizable(false);// 不可更改窗体大小frame.setDefaultCloseOperation(EXIT_ON_CLOSE);// 默认关闭方式frame.setVisible(true);// 窗口可见}class ImagePanel extends JPanel {protected void paintComponent(Graphics g) {super.paintComponent(g);ImageIcon icon = new ImageIcon("src/pic/1.jpg");g.drawImage(icon.getImage(), 0, 0, null);}}}
最终效果

0 0