日期:2014-05-20  浏览次数:20726 次

菜鸟问题:读文本区
2个文本区域,一个按钮,一个文本区域输入了文本,要求点击按钮,会把该文本区域的内容显示到另一个文本区域,请问按钮事件该怎么写(我要逐行读文本,因为要记录行号)?

------解决方案--------------------
我也想知道各~
------解决方案--------------------
for example

JButton btn = new JButton("copy");
JTextArea t1 = new JTextArea();
JTextArea t2 = new JTextArea();
t1.append("abcd\n");
t1.append("efgh\n");

btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] s = t1.getText().split("\n");
for (int i=0; i<s.length; i++) {
t2.append((i+1) + " " + s[i] + "\n");
}
}
});

直接手写的,没有测试过,大概这么个思路,LZ自己参考着改吧

------解决方案--------------------
package net.xiaohai;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class TestMain extends JFrame {
JTextField tf,tf1;
public TestMain() {
super("Copy");
JButton btn = new JButton("Copy");
tf = new JTextField(19);
tf1 = new JTextField(20);
tf1.setEditable(false);

this.getContentPane().add(btn, BorderLayout.SOUTH);
this.getContentPane().add(tf, BorderLayout.WEST);
this.getContentPane().add(tf1, BorderLayout.EAST);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setSize(450, 300);
this.setVisible(true);
btn.addActionListener(new ActionListener() { 
public void actionPerformed(ActionEvent e) { 
String[] s = tf.getText().split("\n");
for (int i=0; i <s.length; i++) { 
tf1.setText((i+1) + " " + s[i] + "\n"); 


}); 

}

public static void main(String[] args) {
new TestMain();
}
}
仅供参考 楼主