Question

Need help writing Java code for this question. CircleFrame class is provided below. what happen after...

Need help writing Java code for this question. CircleFrame class is provided below. what happen after u add the code and follow the requirement?

It would be nice to be able to directly tell the model to go into wait mode in the same way that the model's notify method is called. (i.e. notify is called directly on the model, whereas wait is called indirectly through the suspended attribute.) Try altering the the actionPerformed method of the SliderListener innner class in the CircleFrame class as follows, and see what happens:

    ...
    if (delay == 0) {
      model.wait()
    } else if (delay > 0 && model.getSuspended()) {
      // Restart the model if it is currently suspended.
    ...

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JSlider;

import javax.swing.event.ChangeEvent;

import javax.swing.event.ChangeListener;

/**

* Frame to display circle model and its view.

*

* @author David Brown

* @version 2017-07-17

*/

@SuppressWarnings("serial")

public class CircleFrame extends JFrame {

// ---------------------------------------------------------------

/**

   * Inner class that adds color change functionality to buttons.

   */

private class ButtonListener implements ActionListener {

   @Override

   public void actionPerformed(final ActionEvent e) {

      final JButton button = (JButton) e.getSource();

      final Color color = button.getBackground();

      CircleFrame.this.circlePanel.setColor(color);

   }

}

// ---------------------------------------------------------------

/**

   * Inner class that allows use to alter circle display delay.

   */

private class SliderListener implements ChangeListener {

   @Override

   public void stateChanged(final ChangeEvent arg0) {

      if (!CircleFrame.this.slider.getValueIsAdjusting()) {

       // Update the delay when the slider stops moving.

       final int delay = CircleFrame.this.slider.getValue();

       model.setDelay(delay);

       }

       if (delay > 0 && model.getSuspended()) {

          // Restart the model if it is currently suspended.

          synchronized (model) {

           // Continue execution of this view only after the model

           // acknowledges the notify.

           model.setSuspended(false);

           model.notify();

          }

       }

      }

   }

}

// ---------------------------------------------------------------

/**

   * Inner class that kills the model's thread when the window is closed.

   */

private class DisposeListener extends WindowAdapter {

   @Override

   public void windowClosing(final WindowEvent e) {

      // Cancel the currently running thread.

      model.stop();

   }

}

// ---------------------------------------------------------------

// Class constants

static final int DELAY_INIT = 200;

static final int DELAY_MAX = 400;

static final int DELAY_MIN = 0;

// Class attributes.

private final JButton blueButton = new JButton(" ");

private final JPanel buttonPanel = new JPanel();

private CircleView circlePanel = null;

private CircleModel model = null;

private final JButton greenButton = new JButton(" ");

private final JPanel mainPanel = new JPanel();

private final JButton redButton = new JButton(" ");

private final JButton pinkButton = new JButton(" ");

private final JSlider slider = new JSlider(JSlider.HORIZONTAL,

      CircleFrame.DELAY_MIN, CircleFrame.DELAY_MAX,

      CircleFrame.DELAY_INIT);

/**

   * Constructor.

   *

   * @param model

   * The circle model to display.

   */

public CircleFrame(CircleModel model) {

   this.model = model;

   this.setTitle("Circle");

   circlePanel = new CircleView(model);

   this.setLayout();

   this.registerListeners();

}

/**

   * Registers the slider and button listeners.

   */

private void registerListeners() {

   this.slider.addChangeListener(new SliderListener());

   this.blueButton.addActionListener(new ButtonListener());

   this.greenButton.addActionListener(new ButtonListener());

   this.redButton.addActionListener(new ButtonListener());

   this.pinkButton.addActionListener(new ButtonListener());

   this.addWindowListener(new DisposeListener());

   return;

}

/**

   * Defines the frame layout.

   */

private void setLayout() {

   this.mainPanel.setLayout(new BorderLayout());

   this.slider.setMajorTickSpacing(DELAY_MAX / 4);

   this.slider.setMinorTickSpacing(DELAY_MAX / 16);

   this.slider.setPaintTicks(true);

   this.slider.setPaintLabels(true);

   this.blueButton.setBackground(Color.BLUE);

   this.greenButton.setBackground(Color.GREEN);

   this.redButton.setBackground(Color.RED);

   this.pinkButton.setBackground(Color.PINK);

   this.buttonPanel

       .setLayout(new BoxLayout(this.buttonPanel, BoxLayout.Y_AXIS));

   this.buttonPanel.add(this.redButton);

   this.buttonPanel.add(this.greenButton);

   this.buttonPanel.add(this.blueButton);

   this.buttonPanel.add(this.pinkButton);

   this.mainPanel.add(this.slider, BorderLayout.SOUTH);

   this.mainPanel.add(this.circlePanel, BorderLayout.CENTER);

   this.mainPanel.add(this.buttonPanel, BorderLayout.EAST);

   this.setContentPane(this.mainPanel);

}

}

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.geom.AffineTransform;

import java.beans.PropertyChangeEvent;

import java.beans.PropertyChangeListener;

import javax.swing.JPanel;

/**

* Creates a panel to hold an animated circle.

*

* @author David Brown

* @version 2017-07-17

*/

@SuppressWarnings("serial")

public class CircleView extends JPanel {

// ---------------------------------------------------------------

/**

   * Repaints the circle model.

   */

private class DisplayListener implements PropertyChangeListener {

   @Override

   public void propertyChange(final PropertyChangeEvent arg0) {

      CircleView.this.repaint();

   }

}

// ---------------------------------------------------------------

// Attributes.

private Color color = Color.GREEN;

private CircleModel model = null;

private double scale = 1.0;

/**

   * Constructor.

   *

   * @param model

   * The circle model to display.

   */

public CircleView(final CircleModel model) {

   this.model = model;

   this.registerListeners();

}

@Override

public void paintComponent(final Graphics g) {

   final Graphics2D g2d = (Graphics2D) g;

   g2d.setColor(this.color);

   g2d.clearRect(0, 0, this.getWidth(), this.getHeight());

   this.setScale();

   final AffineTransform at = new AffineTransform();

   at.translate(this.getWidth() / 2.0, this.getHeight() / 2.0);

   at.scale(this.scale, this.scale);

   g2d.setTransform(at);

   g2d.fill(this.model.getCircle());

   return;

}

/**

   * Register the panel listeners.

   */

private void registerListeners() {

   this.model.addPropertyChangeListener(new DisplayListener());

}

/**

   * Sets the circle fill color.

   *

   * @param color

   * The new fill color.

   */

public void setColor(final Color color) {

   this.color = color;

}

/**

   * Calculate the circle to window scaling. Only one scaling is required to

   * preserve the 'circularity' of the circle.

   */

private void setScale() {

   this.scale = Math.min(this.getWidth() / (CircleModel.MAX_RADIUS * 2.0),

       this.getHeight() / (CircleModel.MAX_RADIUS * 2.0));

}

}

import java.beans.PropertyChangeListener;

import java.beans.PropertyChangeSupport;

// -------------------------------------------------------------------------------

/**

* Simple threaded circle. Changes size.

*

* @author David Brown

* @version 2017-07-17

*/

public class CircleModel implements Runnable {

// Class constants.

private static final int INCREMENT = 4;

private static final int INITIAL_DELAY = 100;

public static final int MAX_RADIUS = 100;

public static final int MIN_RADIUS = 12;

// Class attributes.

private final Circle circle = new Circle();

private int delay = CircleModel.INITIAL_DELAY;

private boolean grow = true;

// Allows views to listen to generic changes in the model.

private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

// The suspend / resume flag.

private boolean suspended = false;

// The stop run() flag. 'volatile' means that it is not cached.

private volatile boolean exit = false;

/**

   * Attaches propery change listeners to the model.

   *

   * @param listener

   * The property change listener to attach.

   */

public void addPropertyChangeListener(

      final PropertyChangeListener listener) {

   this.pcs.addPropertyChangeListener(listener);

}

/**

   * @return Returns the current value of <code>circle</code>.

   */

public Circle getCircle() {

   return this.circle;

}

/**

   * @return Returns the current value of <code>suspended</code>.

   */

public boolean getSuspended() {

   return this.suspended;

}

/**

   * Resizes the circle between MIN_RADIUS and MAX_RADIUS.

   */

public void resizeCircle() {

   if (this.circle.getRadius() >= CircleModel.MAX_RADIUS) {

      this.grow = false;

   } else if (this.circle.getRadius() <= CircleModel.MIN_RADIUS) {

      this.grow = true;

   }

   if (this.grow) {

      this.circle.incrementRadius(CircleModel.INCREMENT);

   } else {

      this.circle.incrementRadius(-CircleModel.INCREMENT);

   }

   // Inform listeners the model is updated.

   this.pcs.firePropertyChange(null, null, null);

}

/*

   * (non-Javadoc)

   *

   * @see java.lang.Runnable#run()

   *

   * Must define block as 'synchronized' in order to call <code>wait</code>

   */

@Override

public synchronized void run() {

   try {

      while (!exit) {

       // Continue processing until the current thread is cancelled by

       // an interrupt.

       // Put the current thread to sleep for delay ms.

       Thread.sleep(this.delay);

       this.resizeCircle();

       if (this.suspended) {

          this.wait();

       }

      }

   } catch (final InterruptedException e) {

      // Thread has been interrupted including during sleep or wait.

      // Stops immediately in either case.

      System.out.println("Interrupted!");

   } finally {

      System.out.println("Stopped!");

   }

   return;

}

/**

   * Sets the update delay on the circle. Suspends the changes if the delay is

   * 0. Suspended can only be changed to false from outside the class.

   *

   * @param delay

   * The delay in ms.

   */

public void setDelay(final int delay) {

   this.delay = delay;

   if (this.delay == 0) {

      this.suspended = true;

   }

}

// -------------------------------------------------------------------------------

/**

   * Sets the value of <code>suspend</code>

   *

   * @param suspended

   * The new value for <code>suspend</code>

   */

public void setSuspended(final boolean suspended) {

   this.suspended = suspended;

}

  

// -------------------------------------------------------------------------------

/**

   * Stops the thread entirely.

   */

public void stop() {

   this.exit = true;

}

}

0 0
Add a comment Improve this question Transcribed image text
Know the answer?
Add Answer to:
Need help writing Java code for this question. CircleFrame class is provided below. what happen after...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show...

    In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show when my acceptbutton1 is pressed. One message is if the mouse HAS been dragged. One is if the mouse HAS NOT been dragged. /// I tried to make the Points class or the Mouse Dragged function return a boolean of true, so that I could construct an IF/THEN statement for the showDialog messages, but my boolean value was never accepted by ButtonHandler. *************************ButtonHandler class************************************...

  • fill in the blanks with java code The following code implements a Java timer that looks...

    fill in the blanks with java code The following code implements a Java timer that looks like the application below. . Once the application starts it keeps counting seconds until it is terminated. Timer (sec): 20 You are given a partial implementation of the program. Fill out the missing code to complete the program. import java.awt.*; import java.awt.event.; import java.util."; import javax.swing. *; import javax.swing. Timer; * This program shows a timer that is updated once per second. public class...

  • Debug this java and post the corrected code. /* Creates a simple JPanel with a single...

    Debug this java and post the corrected code. /* Creates a simple JPanel with a single "quit" JButton * that ends the program when clicked. * There are 3 errors, one won't prevent compile, you have to read comments. */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class QuitIt extends JFrame {     public QuitIt() {         startIt(); //Create everything and start the listener     }     public final void startIt() {        //Create the JPanel        JPanel myPanel =...

  • in java coorect this code & screenshoot your output ---------------------------------------------------------------------- public class UNOGame {     /**...

    in java coorect this code & screenshoot your output ---------------------------------------------------------------------- public class UNOGame {     /**      * @param args the command line arguments      */         public static void main(String[] args) {       Scanner input=new Scanner(System.in);          Scanner input2=new Scanner(System.in);                             UNOCard c=new UNOCard ();                UNOCard D=new UNOCard ();                 Queue Q=new Queue();                           listplayer ll=new listplayer();                           System.out.println("Enter Players Name :\n Click STOP To Start Game..");        String Name = input.nextLine();...

  • Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button...

    Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button just hit enter on keyboard to try number -Remove Button Quit import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; // Main Class public class GuessGame extends JFrame { // Declare class variables private static final long serialVersionUID = 1L; public static Object prompt1; private JTextField userInput; private JLabel comment = new JLabel(" "); private JLabel comment2 = new JLabel(" "); private int...

  • Simple java GUI language translator. English to Spanish, French, or German import javax.swing.*; import java.awt.*; import...

    Simple java GUI language translator. English to Spanish, French, or German import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class translatorApp extends JFrame implements ActionListener {    public static final int width = 500;    public static final int height = 300;    public static final int no_of_lines = 10;    public static final int chars_per_line = 20;    private JTextArea lan1;    private JTextArea lan2;    public static void main(String[] args){        translatorApp gui = new translatorApp();...

  • I have currently a functional Java progam with a gui. Its a simple table of contacts...

    I have currently a functional Java progam with a gui. Its a simple table of contacts with 3 buttons: add, remove, and edit. Right now the buttons are in the program but they do not work yet. I need the buttons to actually be able to add, remove, or edit things on the table. Thanks so much. Here is the working code so far: //PersonTableModel.java import java.util.List; import javax.swing.table.AbstractTableModel; public class PersonTableModel extends AbstractTableModel {     private static final int...

  • Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...

    Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Project3 extends JFrame implements ActionListener { private static int winxpos = 0, winypos = 0; // place window here private JButton exitButton, hitButton, stayButton, dealButton, newGameButton; private CardList theDeck = null; private JPanel northPanel; private MyPanel centerPanel; private static JFrame myFrame = null; private CardList playerHand = new CardList(0); private CardList dealerHand = new CardList(0);...

  • JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to...

    JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to maintain a list of shapes drawn as follows: Replace and upgrade all the AWT components used in the programs to the corresponding Swing components, including Frame, Button, Label, Choice, and Panel. Add a JList to the left of the canvas to record and display the list of shapes that have been drawn on the canvas. Each entry in the list should contain the name...

  • Can you please help me to run this Java program? I have no idea why it...

    Can you please help me to run this Java program? I have no idea why it is not running. import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @SuppressWarnings({"unchecked", "rawtypes"}) public class SmartPhonePackages extends JFrame { private static final long serialVersionID= 6548829860028144965L; private static final int windowWidth = 400; private static final int windowHeight = 200; private static final double SalesTax = 1.06; private static JPanel panel;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT