Swing中设置关闭窗口验证与添加背景图片
package com.swing.test;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/** *@Title BackGroundPic.java *@description TODO *@ time 2018-8-31 下午11:11:50 *@author Anderson *@version 1.0 */
public class BackGroundPic extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;//最大的Jpanel层
private JLabel lblBackgroundl;//背景图片标签
/** * Create the frame. */
public BackGroundPic() {
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);//绝对布局
setResizable(false);//不允许用户自定义大小
setSize(612 ,398);//设置Jpanel大小
setLocationRelativeTo(null);//居中
//设置点关闭后什么也不做.为添加关闭窗口验证做铺垫
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
/** * 为整个窗口添加退出确认,前提是 * setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); */
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int isExits = JOptionPane.showConfirmDialog(null, "确认退出吗?",
"Exit", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (isExits == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
});
/**********************设置背景图片***********************/
/** * @author Administrator * getScaledInstance(width,height,hints); * //width,height,hints为方法中的参数 * width the width to which to scale the image. * height the height to which to scale the image. * hints flags to indicate the type of algorithm to use for image resampling. * //指示用于图像重新取样的算法类型的标志,指定缩放的比例算法 */
ImageIcon background = new ImageIcon("./img/login_box.jpg");
background.setImage(
background.getImage().getScaledInstance(
background.getIconWidth(), background.getIconHeight(),
Image.SCALE_DEFAULT
)
);
lblBackgroundl = new JLabel();
lblBackgroundl.setBounds(0, 0, 608, 369);
lblBackgroundl.setIcon(background);
lblBackgroundl.setHorizontalAlignment(0);
getContentPane().add(lblBackgroundl);
System.out.println(
"图片宽: "+background.getIconWidth() +
"高:" + background.getIconHeight()
);
/**********************以上,设置背景图片***********************/
}
/** * Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BackGroundPic frame = new BackGroundPic();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
字符串下拉框的设置
private static JComboBox<String> cobAuth;
cobAuth = new JComboBox<String>();
cobAuth.setBounds(244, 235, 147, 21);
cobAuth.addItem("Leader");//添加下拉内容
cobAuth.addItem("Worker");
//cobAuth.setSelectedIndex(0);//设置默认显示下拉框
contentPane.add(cobAuth);
//获取下拉框值
private static String auth1;
auth1 = (String) cobAuth.getSelectedItem();
密码输入框的设置
private static JPasswordField pwdField;
pwdField = new JPasswordField();
pwdField.setBounds(244, 210, 147, 21);
contentPane.add(pwdField);
//获取密码框值
private static String pwd1;
pwd1 = String.v