Question

In: Computer Science

Enhancing a Movable Circle File MoveCircle contains a program that uses CirclePanel to draw a circle...

Enhancing a Movable Circle


File MoveCircle contains a program that uses CirclePanel to draw a circle and let the user move it by pressing buttons. Save these files to your directory and compile and run MoveCircle to see how it works. Then modify the code in CirclePanel as follows:


1. Add mnemonics to the buttons so that the user can move the circle by pressing the ALT-l, ALT-r, ALT-u, or ALT-d keys.


2. Add tooltips to the buttons that indicate what happens when the button is pressed, including how far it is moved.


3. When the circle gets all the way to an edge, disable the corresponding button. When it moves back in, enable the button again. Note that you will need instance variables (instead of local variables in the constructor) to hold the buttons and the panel size to make them visible to the listener. Bonus: In most cases the circle won’t hit the edge exactly; check for this (e.g., x<0) and adjust the coordinates so it does.

Deliverables:

CirclePanel.java

// ******************************************************************
// MoveCircle.java
//
// Uses CirclePanel to display a GUI that lets the user move
// a circle by pressing buttons.
// ******************************************************************
import java.awt.*;
import javax.swing.*;
public class MoveCircle
{
public static void main(String[] args)
{
JFrame frame = new JFrame ("MoveCircle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.getContentPane().add(new CirclePanel(400,300));
frame.setVisible(true);
}
}

// ******************************************************************
// CirclePanel.java
//
// A panel with a circle drawn in the center and buttons on the
// bottom that move the circle.
// ******************************************************************
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CirclePanel extends JPanel
{
private final int CIRCLE_SIZE = 50;
private int x, y;
private Color c;
//---------------------------------------------------------------
// Set up circle and buttons to move it.
//---------------------------------------------------------------
public CirclePanel(int width, int height)
{
// Set coordinates so circle starts in middle
x = (width/2)-(CIRCLE_SIZE/2);
y = (height/2)-(CIRCLE_SIZE/2);
c = Color.green;
// Need a border layout to get the buttons on the bottom
this.setLayout(new BorderLayout());
// Create buttons to move the circle
JButton left = new JButton("Left");
JButton right = new JButton("Right");
JButton up = new JButton("Up");
JButton down = new JButton("Down");
// Add listeners to the buttons
left.addActionListener(new MoveListener(-20, 0));
right.addActionListener(new MoveListener(20, 0));
up.addActionListener(new MoveListener(0, -20));
down.addActionListener(new MoveListener(0, 20));
// Need a panel to put the buttons on or they'll be on
// top of each other.
JPanel buttonPanel = new JPanel();
buttonPanel.add(left);
buttonPanel.add(right);
buttonPanel.add(up);
buttonPanel.add(down);
// Add the button panel to the bottom of the main panel
this.add (buttonPanel, "South");
}
//----------------------------------------------------------------
// Draw circle on CirclePanel
//----------------------------------------------------------------
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(c);
page.fillOval(x,y, CIRCLE_SIZE, CIRCLE_SIZE);
}
//----------------------------------------------------------------
// Class to listen for button clicks that move circle.
//----------------------------------------------------------------
private class MoveListener implements ActionListener
{
private int dx;
private int dy;
//----------------------------------------------------------------
// Parameters tell how to move circle at click.
//----------------------------------------------------------------
public MoveListener(int dx, int dy)
{
this.dx = dx;
this.dy = dy;
}
//----------------------------------------------------------------
// Change x and y coordinates and repaint.
//----------------------------------------------------------------
public void actionPerformed(ActionEvent e)
{
x += dx;
y += dy;
repaint();
}
}
}

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

//CirclePanel.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CirclePanel extends JPanel {
        private final int CIRCLE_SIZE = 50;
        private int x, y;
        private Color c;

        // declaring buttons outside the constructor (for part 3)
        private JButton left, right, up, down;

        // ---------------------------------------------------------------
        // Set up circle and buttons to move it.
        // ---------------------------------------------------------------
        public CirclePanel(int width, int height) {
                // Set coordinates so circle starts in middle
                x = (width / 2) - (CIRCLE_SIZE / 2);
                y = (height / 2) - (CIRCLE_SIZE / 2);
                c = Color.green;
                // Need a border layout to get the buttons on the bottom
                this.setLayout(new BorderLayout());
                // initialize buttons to move the circle
                left = new JButton("Left");
                right = new JButton("Right");
                up = new JButton("Up");
                down = new JButton("Down");

                // adding mnemonics to the buttons (for part 1)
                left.setMnemonic('l');
                right.setMnemonic('r');
                up.setMnemonic('u');
                down.setMnemonic('d');

                // adding tool tips to the buttons (for part 2)
                left.setToolTipText("circle will be moved 20 spaces to the left");
                right.setToolTipText("circle will be moved 20 spaces to the right");
                up.setToolTipText("circle will be moved 20 spaces up");
                down.setToolTipText("circle will be moved 20 spaces down");

                // Add listeners to the buttons
                left.addActionListener(new MoveListener(-20, 0));
                right.addActionListener(new MoveListener(20, 0));
                up.addActionListener(new MoveListener(0, -20));
                down.addActionListener(new MoveListener(0, 20));
                // Need a panel to put the buttons on or they'll be on
                // top of each other.
                JPanel buttonPanel = new JPanel();
                buttonPanel.add(left);
                buttonPanel.add(right);
                buttonPanel.add(up);
                buttonPanel.add(down);
                // Add the button panel to the bottom of the main panel
                this.add(buttonPanel, "South");
        }

        // ----------------------------------------------------------------
        // Draw circle on CirclePanel
        // ----------------------------------------------------------------
        public void paintComponent(Graphics page) {
                super.paintComponent(page);
                page.setColor(c);
                page.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE);
        }

        // ----------------------------------------------------------------
        // Class to listen for button clicks that move circle.
        // ----------------------------------------------------------------
        private class MoveListener implements ActionListener {
                private int dx;
                private int dy;

                // ----------------------------------------------------------------
                // Parameters tell how to move circle at click.
                // ----------------------------------------------------------------
                public MoveListener(int dx, int dy) {
                        this.dx = dx;
                        this.dy = dy;
                }

                // ----------------------------------------------------------------
                // Change x and y coordinates and repaint.
                // ----------------------------------------------------------------
                public void actionPerformed(ActionEvent e) {
                        x += dx;
                        y += dy;
                        // (for part 3)
                        // if x goes beyond 0, disabling left button, else enabling it
                        if (x <= 0) {
                                left.setEnabled(false);
                        } else {
                                left.setEnabled(true);
                        }
                        // if x+CIRCLE_SIZE goes above screen width, disabling right button,
                        // else enabling it
                        if (x + CIRCLE_SIZE >= getWidth()) {
                                right.setEnabled(false);
                        } else {
                                right.setEnabled(true);
                        }
                        // repeating similar checks with up and down buttons
                        if (y <= 0) {
                                up.setEnabled(false);
                        } else {
                                up.setEnabled(true);
                        }
                        if (y + CIRCLE_SIZE >= getHeight()) {
                                down.setEnabled(false);
                        } else {
                                down.setEnabled(true);
                        }
                        repaint();
                }
        }
}

/*OUTPUT*/


Related Solutions

Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in English (dictionary), to find the number of misspelled words in a story file called Alcott-little-261.txt. Please note that the dictionary words are all lower-cased and there are no punctuation symbols or numbers. Hence it is important that you eliminate anything other than a-z and A-Z and then lower case story words for valid comparisons against the WordList file. When you read each line of...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in...
Write a Java program that uses the file EnglishWordList.txt which contains a collection of words in English (dictionary), to find the number of misspelled words in a story file called Alcott-little-261.txt. Please note that the dictionary words are all lower-cased and there are no punctuation symbols or numbers. Hence it is important that you eliminate anything other than a-z and A-Z and then lower case story words for valid comparisons against the WordList file. When you read each line of...
Write a program that asks the user for a file name. The file contains a series...
Write a program that asks the user for a file name. The file contains a series of scores(integers), each written on a separate line. The program should read the contents of the file into an array and then display the following content: 1) The scores in rows of 10 scores and in sorted in descending order. 2) The lowest score in the array 3) The highest score in the array 4) The total number of scores in the array 5)...
Create a Python program that: Reads the content of a file (Vehlist.txt) The file contains matching...
Create a Python program that: Reads the content of a file (Vehlist.txt) The file contains matching pairs of vehicle models and their respective makes Separate out the individual make and model on each line of the file Add the vehicle make to one list, and the vehicle model to another list; such that they are in the same relative position in each list Prompt the user to enter a vehicle model Search the list containing the vehicle models for a...
[In Python] Write a program that takes a .txt file as input. This .txt file contains...
[In Python] Write a program that takes a .txt file as input. This .txt file contains 10,000 points (i.e 10,000 lines) with three co-ordinates (x,y,z) each. From this input, use relevant libraries and compute the convex hull. Now, using all the points of the newly constructed convex hull, find the 50 points that are furthest away from each other, hence giving us an evenly distributed set of points.
Create a Python program file and . Your program will draw random circles with filled and...
Create a Python program file and . Your program will draw random circles with filled and non-filled color (random colors) and rectangles, fill andnon-fill color (also random colors) on the canvas. At least 10 for each category
Write a java program that contains 3 overloaded static methods for calculating area of a circle,...
Write a java program that contains 3 overloaded static methods for calculating area of a circle, area of a cylinder and volume of a cylinder. Also create an output method which uses JOptionPaneto display instance field(s) and the result of the computing. Then code a driver class which will run and test calling each of these overloaded methods with hard-coded data and display the data and the result of the calculation by calling output method. Thanks!!
Computing A Raise File Salary.java contains most of a program that takes as input an employee’s...
Computing A Raise File Salary.java contains most of a program that takes as input an employee’s salary and a rating of the employee’s performance and computes the raise for the employee. This is similar to question #3 in the pre-lab, except that the performance rating here is being entered as a String—the three possible ratings are “Excellent”, “Good”, and “Poor”. As in the pre-lab, an employee who is rated excellent will receive a 6% raise, one rated good will receive...
Write a C Program that uses file handling operations of C language. The Program should perform...
Write a C Program that uses file handling operations of C language. The Program should perform following operations: 1. The program should accept student names and students’ assignment marks from the user. 2. Values accepted from the user should get saved in a .csv file (.csv files are “comma separated value” files, that can be opened with spreadsheet applications like MS-Excel and also with a normal text editor like Notepad). You should be able to open and view this file...
A cylinder with a movable piston contains 2.00 g of helium, He, at room temperature. More...
A cylinder with a movable piston contains 2.00 g of helium, He, at room temperature. More helium was added to the cylinder and the volume was adjusted so that the gas pressure remained the same. How many grams of helium were added to the cylinder if the volume was changed from 2.00 L to 3.50 L ? (The temperature was held constant.)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT