在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(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)+""); } } }}
以上所述就是本文的全部內容了,希望大家能夠喜歡。