在GUI中,常用文本框和文本區實現數據的輸入和輸出。如果采用文本區輸入,通常另設一個數據輸入完成按鈕。當數據輸入結束時,點擊這個按鈕。事件處理程序利用getText()方法從文本區中讀取字符串信息。對於采用文本框作為輸入的情況,最后輸入的回車符可以激發輸入完成事件,通常不用另設按鈕。事件處理程序可以利用單詞分析器分析出一個個數,再利用字符串轉換數值方法,獲得輸入的數值。對於輸出,程序先將數值轉換成字符串,然后通過setText()方法將數據輸出到文本框或文本區。
【例 11-9】小應用程序設置一個文本區、一個文本框和兩個按鈕。用戶在文本區中輸入整數序列,單擊求和按鈕,程序對文本區中的整數序列進行求和,並在文本框中輸出和。單擊第二個按鈕,清除文本區和文本框中的內容。
import java.util.*;import java.applet.*;import java.awt.*;
import javax.swing.*;import java.awt.event.*;
public class J509 extends Applet implements ActionListener{
JTextArea textA;JTextField textF;JButton b1,b2;
public void init(){
setSize(250,150);
textA=new JTextArea("",5,10);
textA.setBackground(Color.cyan);
textF=new JTextField("",10);
textF.setBackground(Color.pink);
b1=new JButton("求 和"); b2=new JButton("重新開始");
textF.setEditable(false);
b1.addActionListener(this); b2.addActionListener(this);
add(textA); add(textF); add(b1);add(b2);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
String s=textA.getText();
StringTokenizer tokens=new StringTokenizer(s);
//使用默認的分隔符集合:空格、換行、Tab符合回車作分隔符
int n=tokens.countTokens(),sum=0,i;
for(i=0;i<=n-1;i++){
String temp=tokens.nextToken();//從文本區取下一個數據
sum+=Integer.parseInt(temp);
}
textF.setText(""+sum);
}
else if(e.getSource()==b2){
textA.setText(null);
textF.setText(null);
}
}
}
【例 11-10】小應用程序計算從起始整數到終止整數中是因子倍數的所有數。小程序容器用GridLayout布局將界面划分為3行列,第一行是標簽,第二行和第三行是兩個Panel。設計兩個Panel容器類Panel1,Panel2,並分別用GridLayout布局划分。Panel1為1行6列,Panel2為1行4列。然后將標簽和容器類Panel1,Panel2產生的組件加入到窗口的相應位置中。
import java.applet.*;import javax.swing.*;
import java.awt.*;import java.awt.event.*;
class Panel1 extends JPanel{
JTextField text1,text2,text3;
Panel1(){//構造方法。當創建Panel對象時,Panel被初始化為有三個標簽
//三個文本框,布局為GridLayout(1,6)
text1=new JTextField(10);text2=new JTextField(10);
text3=new JTextField(10);setLayout(new GridLayout(1,6));
add(new JLabel("起始數",JLabel.RIGHT));add(text1);
add(new JLabel("終止數",JLabel.RIGHT));add(text2);
add(new JLabel("因子",JLabel.RIGHT));add www.wujiyule88.cn (text3);
}
}
class Panel2 extends JPanel{//擴展Panel類
JTextArea text;JButton Button;
Panel2(){//構造方法。當創建Panel對象時,Panel被初始化為有一個標簽
//一個文本框,布局為GridLayout(1,4)
text=new JTextArea(4,10);text.setLineWrap(true);
JScrollPane jsp=new JScrollPane(text);
Button=new JButton("開始計算");
setLayout(new GridLayout(1,4));
add(new JLabel("計算結果:",JLabel.RIGHT));
add(jsp);
add(new Label());add(Button);
}
}
public class J510 extends Applet implements ActionListener{
Panel1 panel1;Panel2 panel2;
public void init(){
setLayout(new GridLayout(3,1));
setSize(400,200);panel1=new Panel1();panel2=new Panel2();
add(new JLabel("計算從起始數到終止數是因子倍數的數",JLabel.CENTER));
add(panel1);add(panel2);
(panel2.Button).addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==(panel2.Button)){
long n1,n2,f,count=0;
n1=Long.parseLong(panel1.text1.getText());
n2=Long.parseLong(panel1.text2.getText());
f=Long.parseLong(panel1.text3.getText());
for(long i=n1;i<=n2;i++){
if(i%f==0)
panel2.text.append(String.valueOf(i)+"");
}
}
}
}