在Java中,在關桌面開發(fā)方面也是Java的一大應用。但在程序開發(fā)中主要是起輔助的作用的。要編寫桌面開發(fā)程序,需要用到有關圖形界面技術。在Java中主要有awt、swt還有swin三種技術。其中awt和swing是sun公司開發(fā)的,還有一個就是swt它是IBM公司開發(fā)的,但不管是awt、swt還是swing它們的編程思想是很相似的,可以說掌握其中一種那再去理解其它兩種是很容易的。今天我就用swing寫一個有關用戶登陸的小程序。

import javax.swing.*;
import java.awt.event.*;
class  Succed extends JFrame{
    JPanel jpanel = new JPanel();//創(chuàng)建一個面板
    JLabel label = new JLabel("歡迎登陸!"); //創(chuàng)建一個標簽
//定義構造器

public Succed(){
        jpanel.add(label);
        this.add(jpanel);
        this.setBounds(300, 300, 300, 300);
        this.setVisible(true);
    }
}
public class Admin extends JFrame {

    private static final long serialVersionUID = 1L;
    JTextField  text = new JTextField(10);//創(chuàng)建文本框并設置長度
    JPasswordField  pass = new JPasswordField(10);//創(chuàng)建密碼框
    JLabel  jl1 = new JLabel("用戶名");//創(chuàng)建標簽
    JLabel  jl2 = new JLabel("密碼");
    JButton b1 = new JButton("確認");//創(chuàng)建按鈕
    JButton b2 = new JButton("退出");
    JPanel  jp = new JPanel();
    public Admin(){                                    //定義構造器
        this.setTitle("登陸界面");
        jp.setLayout(null);
        jl1.setBounds(30, 20, 80, 30);       //設置各個控件的位置,及關系
        jp.add(jl1);
        jl2.setBounds(30, 70, 80, 30);
        jp.add(jl2);
        text.setBounds(80, 20, 180, 30);
        jp.add(text);
        pass.setBounds(80, 70, 180, 30);
        jp.add(pass);
        b1.setBounds(50, 130, 80, 30);
        b2.setBounds(200, 130, 80, 30);
        jp.add(b1);
        jp.add(b2);
        b1.addActionListener(new ActionListener(){//為確定按鈕添加時間處理
            public void actionPerformed(ActionEvent e){
               if("admin".equals(text.getText())&&"123".equals(pass.getText()))
               {
                   new Succed();
                   }
               else{
                   JOptionPane.showMessageDialog(null,"對不起,賬號或密碼不正確");
               }               
            }
        });
        b2.addActionListener(new ActionListener(){//為取消按鈕添加時間處理
            public void actionPerformed(ActionEvent e){
            System.exit(0);   
            }
        });
        this.add(jp);
        this.setBounds(300, 250, 350, 250);//設置窗口大小
        this.setVisible(true);//設置窗口可見
    }
        public static void main(String[] args){
            new Admin();
        }
}

 

運行結果如圖:

image

在這個程序中我只添加了一個用戶,用戶名為admin,密碼為123.當輸入用戶及密碼后單擊“確定”按鈕,結果為:

DE9VBOEBTM4U[3$KTY(F_UI

0$$N$7_GH5KOR4}ZI~_[%NE

如果輸入信息有誤,則會出現(xiàn)如圖所示信息:

$)F4$SF7YZBJPEC0CE)A7GA

有關用戶登陸界面的程序就寫到這里,在此我想說的是在Java中有關桌面開發(fā)的技術并不是很難,雖然用到的技術很多,但它們的編程思想是相通的。這篇文章就是在我學了swt之后,用了很短時間又用swing寫的,里面涉及到很多的控件及很多的方法,我們沒有必要全都背下來,當然這也是不現(xiàn)實的。在我們編寫桌面程序時,碰到不會的地方,可以去查資料,當然我說的不會只是不會用但原理是清楚的,但具體函數(shù)清楚而已。好了,先寫到這里吧,有不足之處請大家批評指正。