问答题
本程序的功能是将某个字符段在字符串中第一次出现替换为指定的字符串。窗口中有一个文本域、两个文本框和一个按钮,单击按钮后,第一个文本框中所填写的内容在文本域中字符串第一个出现的地方,将被第二个文本框中的内容替换,如图所示。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class exam_62
{
public static void main(String[] args)
{
TextEditFrame frame=new TextEditFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.showJFrame()
;
}
}
class TextEditFrame extends JFrame
{
public TextEditFrame()
{
setTitle("exam_62");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
Container contentPane=getContentPane();
JPanel panel=new JPanel();
JButton replaceButton=new JButton("Replace");
panel.add(replaceButton);
replaceButton.addActionListener(ReplaceAction())
;
from=new JTextField("brown", 8);
panel.add(from);
panel.add(new JLabel("with"));
to=new JTextField("purple", 8);
panel.add(to);
contentPane.add(panel, BorderLayout.SOUTH);
textArea=new JTextArea(8, 40);
textArea.setText
("The quick brown fox jumps over the lazy dog.");
JScrollPane scrollPane=new JScrollPane(textArea);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
public static final int DEFAULT_WIDTH=400;
public static final int DEFAULT_HEIGHT=200;
private JTextArea textArea;
private JTextField from;
private JTextField to;
private class ReplaceAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String f=from.GetText()
;
int n=textArea.getText().indexOf(f);
if (n >= 0 && f.length() > 0)
textArea.replaceRange(to.getText(), n,
n + f.length());
}
}
}
【参考答案】
第1处:frame.show()
第2处:replaceButton.addActionListener(ne......
(↓↓↓ 点击下方‘点击查看答案’看完整答案 ↓↓↓)