问答题
本程序的功能是获得对话框的输入。主窗口中有一个只读的文本域和一个“输入内容”按钮,单击该按钮后弹出一个对话框,对话框中有一个文本框和两个按钮:“确定”和“取消”,在文本框中输入内容,如果单击“确定”按钮后返回主窗口,则把文本框中输入的内容添加到主窗口的文本域中,如果单击“取消”按钮则直接返回主窗口,如图所示。
import java.awt.*;
import java.awt.event.*;
public class exam6 extends Frame implements ActionListener {
boolean inAnApplet=true;
private SimpleDialog dialog;
private TextArea textArea;
String newline;
public exam_6() {
textArea=new TextArea(5, 40);
textArea.setUnEditable(true);
add("Center", textArea);
Button button=new Button("输入内容");
button.addActionListener(this);
Panel panel=new Panel();
panel.add(button);
add("South", panel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (inAnApplet) {
setVisible(false);
dispose();
} else {
System.exit(0);
}
}
});
newline=System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
if (dialog == null) {
dialog=new SimpleDialog(this,"exam_6");
}
dialog.setVisible(true);
}
public void setText(String text) {
textArea.append(text + newline);
}
public static void main(String args[]) {
exam_6 window=new exam_6();
window.inAnApplet=false;
window.setTitle("exam_6");
window.pack();
window.setVisible(true);
}
}
class SimpleDialog extends Dialog implements ActionListener {
TextField field;
exam_6 parent;
Button setButton;
SimpleDialog(Frame dw, String title) {
super(dw, title, false);
parent=(exam_6)dw;
Panel p1=new Panel();
Label label=new Label ("请输入内容: ");
p1.add(label);
field=new TextField(40);
field.addActionListener();
p1.add(field);
add("Center", p1);
Panel p2=new Panel();
p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
Button b=new Button("取消");
b.addActionListener(this);
setButton=new Button("确定");
setButton.addActionListener(this);
p2.add(b);
p2.add(setButton);
add("South", p2);
pack();
}
public void actionPerformed(ActionEvent event) {
Object source=event.getSource();
if ( (source == setButton)
| (source == field)) {
parent.setText(field.getText());
}
field.selectAll();
setVisible(true);
}
【参考答案】
第1处:textArea.setEditable(false)
第2处:field.addActionList......
(↓↓↓ 点击下方‘点击查看答案’看完整答案 ↓↓↓)