编程实例详解(5)
时间:2011-01-16 zdnet 龚赤兵
四、设计图形用户界面(GUI)
以上程序利用面向对象编程的设计方法,较好地实现了Java应用程序。但美中不足的是,没有图形用户界面供用户使用。
如果我们要增加设计图形用户界面,我们就可以将类Sphere交给一个程序员去实现,将用户界面SphereWindow交给另外一个程序员去开发,这就是面向对象编程的好处,可以进行团队开发,而不是作坊式的传统的程序开发方式。
以下是用户界面SphereWindow的实现代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.text.DecimalFormat;
public class SphereWindow extends JFrame
implements ActionListener
{
private JTextField radiusIn, volumeOut, surfAreaOut;
private Sphere balloon;
private DecimalFormat f3 = new DecimalFormat("0.000");
public SphereWindow()
{
super("Spheres: volume and surface area");
JPanel view = new JPanel();
view.setLayout(new GridLayout(6, 2, 10, 10));
view.setBorder(new EmptyBorder(10, 10, 10, 10));
view.add(new JLabel("Radius = ", SwingConstants.RIGHT));
radiusIn = new JTextField(8);
radiusIn.setBackground(Color.yellow);
radiusIn.addActionListener(this);
view.add(radiusIn);
view.add(new JLabel("Volume = ", SwingConstants.RIGHT));
volumeOut = new JTextField(8);
volumeOut.setEditable(false);
volumeOut.setBackground(Color.white);
view.add(volumeOut);
view.add(new JLabel("Surface area = ", SwingConstants.RIGHT));
surfAreaOut = new JTextField(8);
surfAreaOut.setEditable(false);
surfAreaOut.setBackground(Color.white);
view.add(surfAreaOut);
view.add (new JPanel()); // reserved
Container c = getContentPane();
c.add(view, BorderLayout.CENTER);
balloon = new Sphere(0,0,100);
}
public void actionPerformed(ActionEvent e)
// Called automatically when the user
// strikes Enter on the input field
{
String s = radiusIn.getText();
double r = Double.parseDouble(s);
balloon.setRadius(r);
radiusIn.setText(" " + f3.format(r));
volumeOut.setText(" " + f3.format(balloon.volume()));
surfAreaOut.setText(" " + f3.format(balloon.surfaceArea()));
}
public static void main(String[] args)
{
SphereWindow w = new SphereWindow();
w.setSize(300, 250);
w.addWindowListener(new ExitButtonListener());
w.show();
}
}
ExitButtonListener类的代码为:
import java.awt.event.*;
public class ExitButtonListener extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
通过实现上述程序,利用面向对象编程的设计方法,我们将Model(模型,这里是Sphere)与view(视图,这里是SphereWindow)分离开来。并较好地实现了类的封装,类的重用(Sphere)。便于团队开发,迅速提高开发效率。 |