JAVA基础代码分享--求圆面积

问题描述

  用户输入圆的半径,计算并显示圆的面积

代码分享

/**
* @author hpu-gs
* 2015/11/25
*/
public class Circle {
public static Double r;
public static Double m; /**
* 计算圆的面积
*/
public static void main(String[] args) {
System.out.print("请输入圆的半径:");
Scanner in = new Scanner(System.in);
r = in.nextDouble();
m = Math.PI*r*r;
System.out.println("圆的面积是:"+m);
EventQueue.invokeLater(new Runnable() {//事物分配线程,进行显示窗口
@Override
public void run() {
JFrame frame = new SimpleFrame();
frame.setTitle("求圆面积");//设置窗口的左上角标题
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口事件
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;//获取屏幕的宽度
int screenhHeight = screenSize.height;//获取屏幕的长度
frame.setLocation(screenWidth/2-250, screenhHeight/2-100);//设置窗口在屏幕上的显示位置
Image image = new ImageIcon("Image/image.png").getImage();//设置窗口的左上角图标
frame.setIconImage(image);
frame.setVisible(true);//启动显示窗口
}
});
} } //设计窗口
class SimpleFrame extends JFrame{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHE = 200;
public SimpleFrame(){
add(new NotHelloWordComponent());//将文本填充到窗口
pack();//调整窗口大小
// setSize(DEFAULT_WIDTH, DEFAULT_HEIGHE);//设置窗口的大小
}
} //在窗口中显示文本信息
class NotHelloWordComponent extends JComponent{
public static final int MESSAGE_X = 120;
public static final int MESSAG_Y = 100; private static final int DEFAULT_WIDTH = 500;
private static final int DEFAULT_HEIGHE = 200;
public void paintComponent(Graphics g){
g.drawString("半径为:"+new Circle().r+"的圆,面积为:"+new Circle().m, MESSAGE_X, MESSAG_Y);//在窗口中显示文字
}
@Override
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHE);//返回组件的首选大小
}
}
上一篇:Java多线程基础知识篇


下一篇:NODE.JS的基本系统模块操作样例