都说学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
运行截屏: