第2道题的程序:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingExample extends JFrame
{
JMenuBar bar;
JMenu file;
JMenuItem input;
JLabel lblName,lblAge;
SwingExample()
{
setSize(300,300);
setTitle("SwingExample");
bar=new JMenuBar();
file=new JMenu("File");
input=new JMenuItem("input");
lblName=new JLabel();
lblAge=new JLabel();
file.add(input);
bar.add(file);
setJMenuBar(bar);
getContentPane().setLayout(new GridLayout(2,2));
getContentPane().add(lblName);
getContentPane().add(lblAge);
input.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
myDialog dlg=new myDialog();
dlg.show();
}
});
}
public void setNameAndAge(String name,String age)
{
this.lblName.setText("Your name is: "+name);
this.lblAge.setText("Your age is :"+age);
}
class myDialog extends JDialog
{
JLabel lblName,lblAge;
JTextField txtName,txtAge;
JButton btnOk;
myDialog()
{
setSize(200,200);
lblName=new JLabel("Input Name:");
lblAge=new JLabel("Input Age:");
txtName=new JTextField(15);
txtAge=new JTextField(15);
btnOk=new JButton("OK");
getContentPane().setLayout(new FlowLayout());
getContentPane().add(lblName);
getContentPane().add(txtName);
getContentPane().add(lblAge);
getContentPane().add(txtAge);
getContentPane().add(btnOk);
btnOk.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
setNameAndAge(txtName.getText(),txtAge.getText());
hide();
}
});
}
}
}
class mainApp
{
public static void main(String[] args)
{
SwingExample fm=new SwingExample();
fm.show();
}
}