1 import java.awt.*; 2 import javax.swing.*; 3 4 public class Test_15 extends JFrame { 5 public Test_15() { 6 add(new MultiplicationTablePanel()); 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_4"); 13 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 14 frame.setLocationRelativeTo(null); // Center the frame 15 frame.setVisible(true); 16 } 17 } 18 19 class MultiplicationTablePanel extends JPanel { 20 protected void paintComponent(Graphics g) { 21 super.paintComponent(g); 22 23 int x = 10; 24 int y = 40; 25 String s = ""; 26 int i = 0; 27 28 // Display the title 29 g.setColor(Color.red); 30 g.setFont(new Font("Times", Font.BOLD, 20)); 31 g.drawString("Multiplication Table", x+50, y); 32 33 g.setFont(new Font("Times",Font.BOLD,15)); 34 35 y += 30; 36 for (i = 1; i < 10; i++) 37 g.drawString(" " + i, x + 10, y + 10 + i * 20); 38 39 x += 40; 40 for (i = 1; i < 10; i++) { 41 s = s + " " + i; 42 } 43 g.drawString(s, x, y); 44 45 y += 10; 46 g.drawRect(x, y, 200, 200); 47 48 s = ""; 49 y += 20; 50 51 for (i = 1; i < 10; i++) { 52 for (int j = 1; j < 10; j++) { 53 if (i*j < 10) 54 s = s + " " + i * j; 55 else 56 s = s + " " + i * j; 57 } 58 59 g.drawString(s, x, y); 60 s = ""; 61 y += 20; 62 } 63 } 64 }
结果如下: