2009年6月10日水曜日

AWT テキスト操作

テキスト操作

Stringクラスのテキスト編集用メソッド
・文字の取得

char 変数 = String.charAt(int値);
指定したインデックス位置の文字を取得する


・指定したテキストが最初に登場する位置のインデックス番号を取得する

int 変数 = String.indexOf(String);


・テキストの長さを取得する

int 変数 = String.length();


・テキストの始まり/終わりが指定したテキストで始まり/終わりであるか調べる

boolern 値 = String.startsWith(String);
boolern 値 = String.endsWith(String);


・テキストの一部を取得

String = String.substring(int値,int値);
開始位置から終了位置までを取得する


・テキストの置換

String = String.replace(char値,char値);
第一引数にある文字を全て第二引数の文字に置換する
String = String.replaceAll(String,String);
第一引数のテキストを検索し第二引数のテキストに置換する


例.

public class TextApp extends Frame implements ActionListener{

private static final long serialVersionUID = 1L;

TextArea ta1;
TextField tf1,tf2;
Button b1;

public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
new TextApp();
}

public TextApp(){
this.setSize(300,200);
tf1 = new TextField(10);
tf2 = new TextField(10);
Panel p = new Panel();
p.add(tf1);
p.add(tf2);
this.add(p,BorderLayout.NORTH);
ta1 = new TextArea("12345",20,5,TextArea.SCROLLBARS_VERTICAL_ONLY);
this.add(p,BorderLayout.CENTER);
b1 = new Button("Click");
b1.addActionListener(this);
this.add(b1,BorderLayout.SOUTH);
this.setVisible(true);
}

public void actionPerformed(ActionEvent ev){
String str = ta1.getText();
str = str.replaceAll(tf1.getText(),tf2.getText());
ta1.setText(str);
}
}

注)ta1は表示されない

0 件のコメント:

コメントを投稿