1个回答
展开全部
按照你的要求,用Java AWT组件编写的Java程序如下:
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AFC extends Frame implements ActionListener,ItemListener{
CheckboxGroup cg=new CheckboxGroup();
Checkbox cb1=new Checkbox("正方形",true,cg);
Checkbox cb2=new Checkbox("长方形",false,cg);
Label l1=new Label("正方形边长");
Label l2=new Label("长方形长");
Label l3=new Label("长方形宽");
TextField tf1=new TextField(5);
TextField tf2=new TextField(5);
TextField tf3=new TextField(5);
TextField tfArea=new TextField(5);
Button b=new Button("面积");
Panel p=new Panel();
boolean flag=true;
AFC(){
super("求面积");
p.setBackground(Color.CYAN);
b.setBackground(Color.RED);
p.setLayout(null);
cb1.setBounds(20, 5, 100, 30);
cb2.setBounds(150, 5, 100, 30);
l1.setBounds(20, 50, 100, 30);
tf1.setBounds(150, 50, 100, 30);
b.setBounds(20,100, 80, 30);
tfArea.setBounds(150,100, 100, 30);
b.addActionListener(this);
cb1.addItemListener(this);
cb2.addItemListener(this);
p.add(cb1);p.add(cb2);
p.add(l1);p.add(tf1);
p.add(b);p.add(tfArea);
add(p);
setSize(300, 250);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}} );
setVisible(true);
}
@Override
public void itemStateChanged(ItemEvent ie) {
if(ie.getStateChange() == ItemEvent.SELECTED){
if(ie.getItem().equals("正方形")){
p.remove(l2);
p.remove(tf2);
p.remove(l3);
p.remove(tf3);
l1.setBounds(20, 50, 100, 30);
tf1.setBounds(150, 50, 100, 30);
b.setBounds(20,100, 80, 30);
tfArea.setBounds(150,100, 100, 30);
tf1.setText("");
tfArea.setText("");
p.add(l1);
p.add(tf1);
p.validate();
flag=true;
}
if(ie.getItem().equals("长方形")){
p.remove(l1);
p.remove(tf1);
l2.setBounds(20, 50, 100, 30);
tf2.setBounds(150, 50, 100, 30);
l3.setBounds(20, 100, 100, 30);
tf3.setBounds(150, 100, 100, 30);
b.setBounds(20,150, 80, 30);
tfArea.setBounds(150,150, 100, 30);
tf2.setText("");
tf3.setText("");
tfArea.setText("");
p.add(l2);
p.add(tf2);
p.add(l3);
p.add(tf3);
p.validate();
flag=false;
}
}
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==b){
if(flag==true){
double d=Double.parseDouble(tf1.getText().trim());
tfArea.setText(String.valueOf(d*d));
}else{
double d1=Double.parseDouble(tf2.getText().trim());
double d2=Double.parseDouble(tf3.getText().trim());
tfArea.setText(String.valueOf(d1*d2));
}
}
}
public static void main(String[] args) {
new AFC();
}
}
运行结果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询