最近学习了GUI和事件处理,如今已经可以简单的做一个程序,并且加入事件处理了。
其中,我使用了复选框的组件,它的代码如下:
JCheckBox jc1 = new JCheckBox("记住密码");
JCheckBox jc2 = new JCheckBox("自动登录");
通过这两句代码添加了两个复选框
package denglu; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public class zuoye { public static void main(String[]args){ JFrame frm=new JFrame("MM"); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel soPanel = new JPanel(); frm.add(soPanel,BorderLayout.NORTH); JPanel topPanel = new JPanel(); frm.add(topPanel,BorderLayout.EAST ); //图 Icon t3 = new ImageIcon("1191333.gif"); JLabel l71 = new JLabel(t3); l71.setBounds(0,0,t3.getIconWidth(),t3.getIconHeight()); soPanel.add(l71); JPanel wp = new JPanel(new FlowLayout(FlowLayout.CENTER)); JPanel iwp = new JPanel(); wp.add(iwp); iwp.setLayout(new GridLayout(4, 1)); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); JPanel p4 = new JPanel(); JLabel l1 = new JLabel("账号"); JLabel l2 = new JLabel("密码"); JTextField j = new JTextField(15); JPasswordField j1 =new JPasswordField(15); JCheckBox jc1 = new JCheckBox("记住密码"); JCheckBox jc2 = new JCheckBox("自动登录"); JButton jb = new JButton("登录"); JButton jb1 = new JButton("退出"); //事件处理弹窗 jb.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { if(j.getText().equals("notebook")&& String.valueOf(j1.getPassword()).equals("123")) { frm.setVisible(false); Icon icon=new ImageIcon("1966053082.jpg"); JOptionPane.showMessageDialog(null, "登陆成功", "欢迎回来",JOptionPane.INFORMATION_MESSAGE,icon); } else { JOptionPane.showMessageDialog(null, "密码错误", "错误",JOptionPane.ERROR_MESSAGE); } } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub }}); p1.add(l1); p1.add(j); iwp.add(p1); p2.add(l2); p2.add(j1); iwp.add(p2); p3.add(jc1); p3.add(jc2); iwp.add(p3); p4.add(jb); p4.add(jb1); iwp.add(p4); frm.add(wp, BorderLayout.CENTER); ButtonHandler jb1Handler=new ButtonHandler(); jb1.addActionListener(jb1Handler); frm.setBounds(400,200,500,400); frm.setVisible(true); } } class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ System.exit(0); } }
全部代码如上
运行界面如下