問題描述
用戶輸入圓的半徑,計算並顯示圓的面積
代碼分享
/** * @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);//返回組件的首選大小 } }