组合框是由JComboBox类实现的,该组件可设置为编辑状态,在文本框中输入的值会添加到下拉列表中。在创建时,,可用构造方法JComboBox(Object []items)直接初始化组合框包含的选项。使用addItem方法添加插入选项。我做的界面代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Ex8_1_UseQQ{
public static void main(String[] args){
//设置窗体并设置窗体标题
JFrame frm =new JFrame("QQ登录");
//设置窗体关闭方式
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(null);
JLabel userLabel =new JLabel();
//创建QQ输入框
JLabel ID=new JLabel("Q Q:");
ID.setBounds(20,40,50,20);
ID.setForeground(Color.BLUE);
JComboBox idfield = new JComboBox();
idfield.setBounds(75,40,200,20);
idfield.addItem("619504051");
idfield.addItem("234325434");
idfield.addItem("543547542");
//创建密码输入框
JLabel password = new JLabel("密码:");
password.setBounds(20,100,50,20);
password.setForeground(Color.BLUE);
JPasswordField password1=new JPasswordField();
password1.setBounds(75,100,200,20);
//创建登录及退出按钮
JButton loginBtn =new JButton("登录");
loginBtn.setBounds(65,200,60,20);
loginBtn.addActionListener(new ActionListener(){
@ Override
public void actionPerformed(ActionEvent arg0) {
if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(null,"确定登录")){
System.exit(0);}
}});
JButton cancelBtn =new JButton("退出");
cancelBtn.setBounds(165,200,60,20);
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(null,"确定退出")){
System.exit(0);}
}
});
//选择框
JCheckBox cloak =new JCheckBox("隐身登录");
cloak.setBounds(20,150,100,20);
JCheckBox remember =new JCheckBox("记住密码");
remember.setBounds(150,150,100,20);
//加入窗体容器
frm.add(userLabel);
frm.add(ID);
frm.add(idfield);
frm.add(password);
frm.add(password1);
frm.add(loginBtn);
frm.add(cancelBtn);
frm.setBounds(400,500,300,310);
frm.setVisible(true);
//frm.add(picture);
frm.add(cloak);
frm.add(remember);
}
}
效果如图所示: