Here we will learn to split the String in parts on the basis of tokens provided
Using StringTokenizer
package thanhcs.bai10;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Bai10_JtextArea extends JFrame implements ActionListener {
JTextField txtfiel;
JTextArea areatxt;
public Bai10_JtextArea() {
// TODO Auto-generated constructor stub
JPanel jp = new JPanel();
jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
jp.add(new JLabel("Nhap Chuoi va nhan Enter", SwingConstants.CENTER));
jp.add(txtfiel = new JTextField(20));
add(jp, BorderLayout.NORTH);
add(areatxt = new JTextArea(), BorderLayout.CENTER);
txtfiel.addActionListener(this);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 270);
setResizable(false);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
Bai10_JtextArea a = new Bai10_JtextArea();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==txtfiel)
{
String total = "";
String temp[] = new String[30];
String item = txtfiel.getText();
total = item + "\n" + "They are : \n";
StringTokenizer tokens = new StringTokenizer(item, " ");
int dem = tokens.countTokens();
for(int i = 0 ; i < dem ; i++)
{
temp[i] = tokens.nextToken();
}
for(int j = 0 ; j < temp.length;j++)
{
if(temp[j]!=null)
{
total+=temp[j]+"\n";
}
}
areatxt.setText(total);
}
}
}
No comments:
Post a Comment