CDKEY生成器 – JAVA編程語言程序開發技術文章

無聊 寫著好玩的.

[java]
package randomString; 
 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 
 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
 
public class Main { 
 
    /**
     * 生成隨機字符串
     */ 
    private JFrame jFrame; 
    private JPanel jp; 
    private JButton jb; 
    private JTextField tf,tf2; 
    private JLabel  jl; 
    public Main(){ 
        jFrame = new JFrame("字符串生成工具  by:smile"); 
        jp = new JPanel(); 
        jb = new JButton("生成(s)"); 
        tf = new JTextField(20); 
        tf2 = new JTextField(3); 
        jl = new JLabel("位"); 
        MyActionListener mal = new MyActionListener(); 
 
        jp.add(tf); 
        jp.add(jb); 
        jp.add(tf2); 
        jp.add(jl); 
        jFrame.add(jp); 
 
        jb.setMnemonic('s'); 
        jb.addActionListener(mal); 
         
        jFrame.pack(); 
        int w = jFrame.getToolkit().getScreenSize().width;//寬度 
        int h = jFrame.getToolkit().getScreenSize().height;//高度 
        jFrame.setLocation(w/2-200,h/2-30); 
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        jFrame.setVisible(true); 
    } 
    class MyActionListener implements ActionListener{ 
        @Override 
        public void actionPerformed(ActionEvent e) { 
            if(e.getSource().equals(jb)){ 
                try { 
                    tf.setText(Main.getRandomString(Integer.parseInt(tf2.getText()))); 
                } catch (Exception x) { 
                    JOptionPane.showMessageDialog(null, "請輸入數字"); 
                } 
            } 
        } 
    } 
    public static String getRandomString(int length) { //length表示生成字符串的長度 
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";    
        Random random = new Random();    
        StringBuffer sb = new StringBuffer();    
        for (int i = 0; i < length; i++) {    
            int number = random.nextInt(base.length());    
            sb.append(base.charAt(number));    
        }    
        return sb.toString(); 
    }   
    public static void main(String[] args) { 
        new Main(); 
    } 

 

摘自 Small-bao的小窩

發佈留言