21 Jan 2012 [ 201 hw ]

Create a separate class file for each problem, and email all files as attachments to me at jal2016@email.vccs.edu with subject CSC 201 HW3.

Due Tuesday, Jan 31.

1

Create a program in a class called BoxString that reads a line of text, and then prints it in upper case and surrounded by a box (nicely formatted).

For example, if you type Bananas!, your program should print:

+----------+
| BANANAS! |
+----------+

Take a look at the methods available for the String class, since you'll need to use some of them; see especially length(). Here's a possible setup for your program:

import java.util.Scanner;

public class BoxString {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String line = input.nextLine();
        // Print line surrounded by a nice box.
    }
}

2

Experiment with the Java 2D graphics API using the Graphics2D class. Starting with the template below, draw a picture using different colors and shapes. Discover what to draw by investigating the methods available to g2. The Color class is useful for changing the drawing color. Try to use loops and conditional statements to create interesting effects.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;

public class DrawingExample extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        // Put code in this method to draw to the panel.
        // The main graphics drawing object:
        Graphics2D g2 = (Graphics2D) g;
        // Here's an example.
        // (Replace this with your own more interesting drawing.)
        for (int i = 0; i < 30; i++) {
            Color col;
            if (i % 2 == 0)
                col = Color.BLUE;
            else
                col = Color.PINK;
            g2.setColor(col);
            g2.fillRect(100 + i * 5, 100 + i * 5, 300 - i * 10, 300 - i * 10);
        }
    }
    
    // Below is basic setup code that we'll discuss in more detail later.

    public static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("DrawingExample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(500, 500));
        
        // Add our drawing panel.
        DrawingExample draw = new DrawingExample();
        frame.getContentPane().add(draw);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}