Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Write a program that displays a multiplication table in a panel using the drawing methods, as shown in Figure 13.27a.
- */
- import java.awt.*;
- import javax.swing.*;
- @SuppressWarnings("serial")
- public class DisplayAMultiplicationTable extends JFrame
- {
- // Constructor
- public DisplayAMultiplicationTable()
- {
- add(new MultiplicationTablePanel());
- }
- // Main method
- public static void main(String[] args)
- {
- DisplayAMultiplicationTable frame = new DisplayAMultiplicationTable();
- frame.setSize(300, 400);
- frame.setTitle("Exercise 13_04");
- frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
- frame.setLocationRelativeTo(null);
- frame.setVisible(true);
- }
- }
- @SuppressWarnings("serial")
- // New class
- class MultiplicationTablePanel extends JPanel
- {
- @Override
- protected void paintComponent(Graphics g)
- {
- super.paintComponent(g);
- // Declaration
- int x = 10, y = 40, i = 0; // x & y = start point for "paint brush"
- String s = "";
- // Display the title
- g.setColor(Color.RED);
- g.setFont(new Font("Times", Font.BOLD, 20));
- g.drawString("Multiplication Table", x + 50, y);
- // Font for numbers
- g.setFont(new Font("Times", Font.BOLD, 15));
- y += 30; // Move down 30 pixels
- for(i = 1; i < 10; i++) // Vertical row
- g.drawString(" " + i, x + 10, y + 10 + i * 20); // Spaces move line left/right, prints downwards
- x += 40; // Move right 40 pixels
- for(i = 1; i < 10; i++)
- {
- s = s + " " + i; // Create full string
- }
- g.drawString(s, x, y); // Then print horizontally (top)
- y += 10;
- g.drawRect(x, y, 200, 200); // Draw border
- s = ""; // Reset string
- y += 20; // Move down 20
- // x does not need to be reset string will add spaces after last printed vertical numbers
- for(i = 1; i < 10; i++)
- {
- for(int j = 1; j < 10; j++)
- {
- if(i * j < 10)
- s = s + " " + i * j; // Builds entire row with spaces
- else
- s = s + " " + i * j; // Accounts for single and double digits
- }
- g.drawString(s, x, y); // Print built string
- s = ""; // Reset string
- y += 20; // Move down one row
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment