使用循环语句绘制图案-2

都说学Java可以跳过Swing,其实我觉得Swing还是挺有意思的。

至少看到自己的代码实现的复杂的图案,感觉到了一点成就感。

 

代码如下:

//Graphics Exercise 4.2
/*Using loops and control statements to draw lines can lead 
* to many interesting designs Graphics101.java
*/
//Creating JFrame to display DrawPanel.
import javax.swing.JFrame;
import java.awt.Graphics; 
import javax.swing.JPanel;

public class Graphics101_2 extends JPanel
{
	// draws an X from the corners of the panel
	public void paintComponent(Graphics g)
	{
	  // call paintComponent to ensure the panel displays correctly
	  super.paintComponent(g);
	  
	  int width = getWidth(); // total width   
	  int height = getHeight(); // total height
	  int step=1;

	  // draw a line from the upper-left to the lower-right
	  while (step<=15)
	  {
		  g.drawLine(0, height/15*(step-1), width/15*step, height);
		  g.drawLine(width/15*(15-step+1), 0, 0, height/15*step);
		  g.drawLine(width, height/15*(15-step+1), width/15*(15-step+1), 0);
		  g.drawLine(width/15*step, height, width, height/15*(15-step+1));
		  step++;
	  }
	} 

	
	public static void main(String[] args)
{
// create a panel that contains our drawing
Graphics101_2 panel = new Graphics101_2();

// create a new frame to hold the panel
JFrame application = new JFrame();

// set the frame to exit when it is closed
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

application.add(panel); // add the panel to the frame      
application.setSize(250, 250); // set the size of the frame
application.setVisible(true); // make the frame visible    
} 
} // end class DrawPanelTest

 

运行截屏:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值