1 import java.awt.*; 2 import javax.swing.*; 3 4 public class Test_15 extends JFrame { 5 public Test_15() { 6 add(new PiramidPanel()); 7 } 8 9 public static void main(String[] args) { 10 Test_15 frame = new Test_15(); 11 frame.setSize(300, 400); 12 frame.setTitle("Exercise15_5"); 13 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 14 frame.setLocationRelativeTo(null); // Center the frame 15 frame.setVisible(true); 16 } 17 } 18 19 class PiramidPanel extends JPanel { 20 protected void paintComponent(Graphics g) { 21 super.paintComponent(g); 22 23 int x = 10, y =20; 24 String s = ""; 25 for(int i=1 ; i < getHeight() ; i++){ 26 for(int j=0; j < i && j < getWidth(); j++){ 27 s = s + " " + (j+1); 28 } 29 30 g.drawString(s, x, y); 31 y += 20; 32 s = ""; 33 } 34 35 } 36 }
Test_15.java
由于在PiramidPanel类中对于行和列的宽度使用了getWidth()和getHeight()函数做限制,所以在拖动窗口时,会根据窗口大小动态调整显示的行和列数。
效果图:
时间: 2024-10-25 22:01:45