工作筆記5.JAVA文字框驗證碼,5.java文字框驗證碼
本文主要內容為:利用JAVA文字框製作驗證碼。
設計思路:
1、頁面載入時,自動產生驗證碼。
2、後JS判定驗證碼是否輸入正確
優點:
代碼簡潔,便於使用。頁面中可直接判定驗證碼的正確性,無需傳到後台Action中。
缺點:
由於本驗證碼是由text製作,容易被瀏覽器抓取/手動copy,丟失了其本質特性(安全性)。
<script type="text/javascript">var code ; //在全域 定義驗證碼function createCode(){ code = "";var codeLength = 4;//驗證碼的長度var checkCode = document.getElementById("checkCode");var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');// 所有候選組成驗證碼的字元,當然也可以用中文的 for(var i=0;i<codeLength;i++){ var charIndex = Math.floor(Math.random()*34);code +=selectChar[charIndex]; }if(checkCode){checkCode.className="code";checkCode.value = code;} document.getElementById("code").focus();}function check(){ if(document.getElementById("code").value.replace(/\\s/g,'') != code ){alert("驗證碼輸入錯誤!區分大小寫");createCode();//重新整理驗證碼document.getElementById("code").focus();return false;} }</script>
</pre><pre code_snippet_id="501094" snippet_file_name="blog_20141029_2_4692873" name="code" class="html"><body onload="javascript:createCode();"><s:form action="user_login" onsubmit="return check()"><input type="text" id="code" class="dz" style="width: 110px;" /><input type="text" onclick="createCode()" readonly="readonly" id="checkCode" class="code" title="換一張"style="width: 68px; height: 27px; cursor:not-allowed" /></s:form></body>
JAVA 文字框
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class myFrame extends JFrame implements ActionListener{
JTextField price ;
JTextField amount ;
JTextField total;
public CountNumber (){
JFrame f = new JFrame("計算價格");
JPanel p = new JPanel();
JTextField price = new JTextField(10);
JTextField amount = new JTextField(10);
JTextField total= new JTextField(10);
JLabel label1 = new JLabel("單價");
JLabel label2 = new JLabel("數量");
JLabel label3 = new JLabel("總價");
JButton btn = new JButton("計算總價");//建立文字框,標籤,按鈕,內容面板,頂層容器
btn.addActionListener(this);
p.add(label1);p.add(price);
p.add(label2);p.add(amount);
p.add(btn);
p.add(label3);p.add(total);
f.add(p);
f.setVisible(true);//使其可見
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//關閉視窗
f.setBounds(50,50,50,50);
f.pack();//將組件添加到頂層容器,並顯示出來
}
public void actionPerformed (ActionEvent e){
String p =price.getText();
String a =amount.getText();
int p1 = Integer.parseInt(p);
int a1 = Integer.parseInt(a);
if(e.getActionCommand().equals("計算總價")){
int t = p1*a1;
total.setText(t+"");
}
}
public static void main(String args[]){
new myFrame();
}
}
//說實話,運行時,有點小錯,但不知道為啥錯了,請......餘下全文>>
一個java文字框的問題
String txt=t1.getText() 就能取到啊
,不過你這樣的寫法應該取不到t1這個文字框。不如這樣寫。
t1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String txt=t1.getText()
}
});