Swing图形绘制(长方形、椭圆、同心圆及直方图)

感觉自己的图形分析有待增强啊,还达不到想什么就能画什么的程度。大哭

代码如下:

ackage example;

import java.awt.Graphics;

//Fig. 5.27: ShapesTest.java, modified by pandenghuang@163.com
//Test application that displays class Shapes.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Graphics; //handle the display

public class ShapesTest
{
	
	public static class Shapes extends JPanel
	{
	private int choice; // user's choice of which shape to draw

	// constructor sets the user's choice
	public Shapes(int userChoice)
	{
	   choice = userChoice;
	} 

	// draws a cascade of shapes starting from the top-left corner
	public void paintComponent(Graphics g)
	{
	   super.paintComponent(g);
	   int width = getWidth(); // total width   
	   int height = getHeight(); // total height
	   int barHorizontalDistance=width/11;
	   int barVerticalDistance=height/11;
	   
	   for (int i = 0; i < 10; i++)
	   {
	      // pick the shape based on the user's choice
	      switch (choice)
	      {
	         case 1: // draw rectangles
	            g.drawRect(10 + i * 10, 10 + i * 10, 
	               50 + i * 10, 50 + i * 10);
	            break;
	         case 2: // draw ovals
	            g.drawOval(10 + i * 10, 10 + i * 10, 
	               50 + i * 10, 50 + i * 10);
	            break;
	         case 3: // draw concentric circles
	             g.drawOval(width/2-(i+1)*10, height/2-(i+1)*10, 
	            		 10+20*i,  10+20*i);
	             break;
	         case 4: // draw bar chart
	             g.drawRect(i * barHorizontalDistance, height - i * barVerticalDistance, 
	                20, height + i * height/11);
	             break;
	      } 
	   } 
	} 
	} 
public static void main(String[] args)
{
   // obtain user's choice
   String input = JOptionPane.showInputDialog(
      "输入1画长方形\n" +
      "输入2画圆形\n"+
	  "输入3画同心圆\n"+
	  "输入4画条形图");
   
   int choice = Integer.parseInt(input); // convert input to int
   
   // create the panel with the user's input
   Shapes panel = new Shapes(choice);
   
   JFrame application = new JFrame(); // creates a new JFrame

   application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   application.add(panel); 
   application.setSize(300, 300); 
   application.setVisible(true); 
}
} // end class ShapesTest


运行截屏:




  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值