网友您好, 请在下方输入框内输入要搜索的题目:
本题中,通过菜单“Connect”显示一个对话框,单击“ok”按钮后,所填写的内容就会传回到主窗口并显示出来。
import java.awt.*
import java.awt.event.*;
import javax.swin9.*;
public class java3 extends JFrame. implements ActionL-
istener{
public java3(){
setTitle("java3");
setSize(300,300);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
JMenuBar mbar = new JMenuBar();
setJMenuBar(bar);
JMenu fileMenu=new JMenu("File");
mbar.add(fileMenu);
connectltem=new JMenuhem("Connect");
connecthem.addActionListener(this);
fileMenu.add(connecthem);
exithem=new JMenuhem("Exit");
exithem.addActionListener(this);
fileMenu.add(exithem);
}
public void actionPerformed(ActionEvent evt){
Object source=evt.getSource();
if(source= =connecthem){
Connectlnfo transfer=new ConnectInfo ("your-
name","pw");
if(dialog= =null)
dialog=new ConnectDialog(this);
if(dialog.showDialog(transfer)){
String uname=transfer.username;
String pwd=transfer.password;
Container contentPane=getContentPane();
contentPane.add(new JLabel("username="+
uname+",password="+pwd),"South");
validate();
}
}
else if(source= =exitltem)
System.exit(0);
}
public static void main(String[]args){
JFrame. f=new java3();
f.show();
}
private ConnectDialog dialog=null;
private JMenuhem connecthem;
private JMenuhem exithem;
}
class Connectlnfo{
public String username;
public String password;
public Connectlnfo(String U,String p){
username=u;password=P;
}
}
class ConnectDialog extends JDialog implements Ac-
tionListener{
public ConnectDialog(){
super(parent,"Connect",true);
Container contentPane=getContentPane();
JPanel pl=new JPanel();
pl.setLayout(new GridLayout(2,2));
pl.add(newJLabel("User name:"));
pl.add(username=new JTextField(""));
pl.add(new JLabel("Password:"));
pl.add(password=new JPasswordField(""));
contentPane.add("Center",pl);
Panel p2=new Panel();
okButton=addButton(p2,"ok");
cancelButton=addButton(p2。"Cancel");
contentPane.add("South",p2);
setSize(240,120);
}
JButton addButton(Container C,String name){
JButton button=new JButton(name);
button.addActionListener(this);
C.add(button);
return button;
}
public void actionPerformed(ActionEvent evt){
object source=evt.getSource();
if(source= =okButton){
ok=true:
setVisible(false);
}
else if(source= =cancelButton)
setVisible(false);
}
public void showDialog(Connectlnfo transfer){
username.setText(transfer.username);
password.setText(transfer.password);
ok=false;
show();
if(ok){
transfer.username=username.getText();
transfer.password=new String(password.get-
Password());
}
return ok;
}
private JTextField username
private JPasswordField password;
private boolean ok;
private JButton okButton;
private JButton cancelButton;
}
参考答案