JComboBox实现当前所选项功能和JFrame窗口释放资源的dispose()方法

时间:2023-03-09 22:18:30
JComboBox实现当前所选项功能和JFrame窗口释放资源的dispose()方法

JComboBox有一个

SelectedItem属性,所以使用getSelectedItem()就可以得到当前选中值.

 package ltb20180106;

 import javax.swing.*;
import java.awt.event.*;
import java.awt.*; public class UserLoginApp { private JFrame jf;
private JLabel name;
private JLabel user;
private JLabel password;
private JButton confirm;
private JButton cancel;
private JButton quit; private JPanel p1;
private JPanel p2;
private JpanelAction p3;
private JPanel p4; private JComboBox <String> juser;
private JTextField jname;
private JPasswordField jpassword; private String[] s= {"学生用户","教师用户"}; private String ss;
private char[] c;
private String bname;
private String item; public UserLoginApp() { try { jf=new JFrame("用户登录");
jf.setSize(250, 160);
jf.setLayout(new BorderLayout()); name=new JLabel("名字:");
password=new JLabel("密码:");
user=new JLabel("用户类型"); juser=new JComboBox<String>(s);
jname=new JTextField();
jpassword=new JPasswordField(); confirm=new JButton("确定");
cancel=new JButton("取消");
quit=new JButton("退出"); p1=new JPanel();
p1.setLayout(new BoxLayout(p1,BoxLayout.Y_AXIS));//允许垂直或水平布置多个组件的布局管理器
p1.add(user);
p1.add(name);
p1.add(password);
p1.setSize(100,100); p2=new JPanel();
p2.setLayout(new BoxLayout(p2,BoxLayout.Y_AXIS));
p2.add(juser);
p2.add(jname);
p2.add(jpassword);
p2.setSize(150,100); p3=new JpanelAction();
p3.setLayout(new FlowLayout());
p3.add(confirm);
p3.add(cancel);
p3.add(quit);
confirm.addActionListener(p3);
cancel.addActionListener(p3);
quit.addActionListener(p3); p4=new JPanel();
p4.setLayout(new FlowLayout());
p4.add(p1);
p4.add(p2); jf.add(p4,BorderLayout.NORTH);
jf.add(p3,BorderLayout.CENTER); jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null); }catch(Exception e) { System.out.println(e.getMessage()); } } @SuppressWarnings("serial")
class JpanelAction extends JPanel implements ActionListener { public void actionPerformed(ActionEvent e)
{ bname=e.getActionCommand();//关键的地方 if(bname.equals("确定")) { ss=jname.getText();
c=jpassword.getPassword();
item=(String)juser.getSelectedItem();// JComboBox 当前所选项 if(ss.equals("")) { name.setText("用户名不能为空"); } else if(c.length==0) { password.setText("密码不能为空"); }else if(item.equals("学生用户")) { if(ss.equals("s")&&new String(c).equals("s")) {//密码字符转化字符串处理 name.setText("登录成功");
password.setText("登录成功");
}
System.out.println("学生"); }else if(item.equals("教师用户")) { if(ss.equals("t")&&new String(c).equals("t")) {//密码字符转化字符串处理 name.setText("登录成功");
password.setText("登录成功"); } System.out.println("教师");
} }else if (bname.equals("取消")) { jname.setText("");
jpassword.setText(""); }else if(bname.equals("退出")){ jf.dispose();//释放由此 Window、其子组件及其拥有的所有子组件所使用的所有本机屏幕资源。
}
} } public static void main(String[] args) { new UserLoginApp();
} }

JComboBox实现当前所选项功能和JFrame窗口释放资源的dispose()方法