Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1050 karma points I\'m posting three questions for the same question so answer t

ID: 3629832 • Letter: 1

Question

1050 karma points

I'm posting three questions for the same question so answer the 3 questions (same answer) so you get 1050 karma points

Exercising the model-view-controller pattern using Java Swing.

The work is about creating a graphical view (another view beside the textual view) for a right triangle model. The graphical view displays the same changes as the textual view when the changes are made to the right triangle model through the textual view. You may use the same controller for the graphical view as the textual view or create another one dedicated to the graphical view. The user will not directly interact with the graphical view. It is solely for displaying the changes made through the textual view. This will make the work simpler.

Explanation / Answer

//GraphicView.java

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

/**
* Graphical view for a RightTriangle.
*/
class GraphicView extends JPanel implements Observer {

private int modelBase;     // base of model (pixels)
private int modelHeight;   // height of model (pixels)
private final static int BASE_X = 10;
// offset of drawing from left edge of panel (pixels)
private final static int BASE_Y = 10;
// offset of drawing from top of panel (pixels)

/**
   * Create a graphic view for the specified RightTriangle.
   */
public GraphicView (RightTriangle model) {
    super();
    model.addObserver(this);
    update(model,null);
}

/**
   * Update the view with current model state.
   */
public void update (Observable model, Object arg) {
    getModelState((RightTriangle)model);
    repaint();
    Container w = getTopLevelAncestor();
    if (w instanceof Window)
      ((Window)w).pack();
}

/**
   * Draw the triangle on this JPanel.
   */
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(getForeground());
    g.drawLine(BASE_X,BASE_Y+modelHeight,
               BASE_X+modelBase,BASE_Y+modelHeight);
    g.drawLine(BASE_X,BASE_Y,
               BASE_X,BASE_Y+modelHeight);
    g.drawLine(BASE_X,BASE_Y,
               BASE_X+modelBase,BASE_Y+modelHeight);
}

/*
   * Define preferred and minimum size so that the triangle fits.
   */
public Dimension getPreferredSize () {
    return new Dimension(2*BASE_X+modelBase, 2*BASE_Y+modelHeight);
}

public Dimension getMinimumSize () {
    return getPreferredSize();
}

/*
   * Get the properties of the model.
   */
private void getModelState (RightTriangle model) {
    modelBase = model.base();
    modelHeight = model.height();
}
}

//RightTriangle.java

/**
* A right triangle. Units assumed to be pixels.
*/
public class RightTriangle extends java.util.Observable {

// the sides of the triangle
private int base;
private int height;
private int hypotenuse;

/**
   * Create a right triangle with the specified base and height.
   * @require    base >= 0 && height >= 0
   */
public RightTriangle (int base, int height) {
    this.base = base;
    this.height = height;
    setHypotenuse();
}

/**
   * The base.
   * @ensure     result >= 0
   */
public int base () {
    return this.base;
}

/**
   * The height.
   * @ensure     result >= 0
   */
public int height () {
    return this.height;
}

/**
   * The hypotenuse.
   * @ensure     result >= 0
   */

public int hypotenuse () {
    return this.hypotenuse;
}

/**
   * Change base.
   * @require    newBase >= 0
   */
public void setBase (int newBase) {
    this.base = newBase;
    setHypotenuse();
    setChanged();
    notifyObservers();
}

/**
   * Change height.
   * @require    newHeight >= 0
   */
public void setHeight (int newHeight) {
    this.height = newHeight;
    setHypotenuse();
    setChanged();
    notifyObservers();
}

/*
   * Adjust hypotenuse.
   */
private void setHypotenuse () {
    this.hypotenuse = (int) Math.round(Math.sqrt(base*base + height*height));
}
}

//RightTriangleViewer.java

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

/**
* Create an editable RightTriangle and View it.
*/
public class RightTriangleViewer {

public static void main (String[] args) {
    JFrame f = new JFrame("Triangle View 1");
    JFrame g = new JFrame("Triangle View 2");
    RightTriangle model = new RightTriangle(1,1);
    TextView view = new TextView(model);
    GraphicView gv= new GraphicView(model);
    f.getContentPane().add(view, BorderLayout.CENTER);
    g.getContentPane().add(gv, BorderLayout.CENTER);
    f.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          e.getWindow().dispose();
        }
        public void windowClosed(WindowEvent e) {
          System.exit(0);
        }
      }
    );
    g.addWindowListener(
              new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                  e.getWindow().dispose();
                }
                public void windowClosed(WindowEvent e) {
                  System.exit(0);
                }
              }
            );
    f.pack();
    g.pack();
    f.setVisible(true);
    g.setVisible(true);
}
}

//RTLogger.java

import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;

/**
* RTLogger logs changes in a RightTriangle to a file.
*/
class RTLogger implements Observer {

private PrintWriter logFile;
private int modelBase;
private int modelHeight;

/**
   * Create a RightTriangle logger, to log changes in the
   * specified model to the specified log file.
   */
public RTLogger (RightTriangle model, String fileName,
                   Window application) throws java.io.IOException {
    logFile = new PrintWriter(new FileOutputStream(fileName));
    application.addWindowListener(new WindowAdapter() {
      public void windowClosing (WindowEvent e) {
        logFile.close();
      }
    });
    getModelState(model);
    logFile.println(modelBase + " " + modelHeight);
    model.addObserver(this);
}

/**
   * Close the log file.
   */
public void close () {
    logFile.close();
}

/**
   * Log when model changes state.
   */
public void update (Observable model, Object arg) {
    getModelState((RightTriangle)model);
    logFile.println(modelBase + " " + modelHeight);
}

/*
   * Get the properties of the model.
   */
private void getModelState (RightTriangle model) {
    modelBase = model.base();
    modelHeight = model.height();
}
}

//TextView.java

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

/**
* View for a RightTriangle, as three text fields.
*/
class TextView extends JPanel implements java.util.Observer {

private final static int FIELD_SIZE = 16;
private TVController controller;
private JTextField base;
private JTextField height;
private JTextField hypotenuse;

/**
   * Create a view for the specified RightTriangle.
   */
public TextView (RightTriangle model) {
    super();
    setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
   
    constraints.gridx = 0;
    constraints.gridy = GridBagConstraints.RELATIVE;
    constraints.anchor = GridBagConstraints.EAST;
    constraints.insets = new Insets(5,5,5,5);
    add(new JLabel("Base"),constraints);
    add(new JLabel("Height"),constraints);
    add(new JLabel("Hypotenuse"),constraints);
   
    constraints.gridx = 1;
   
    base = new JTextField(FIELD_SIZE);
    base.setActionCommand("Base");
    add(base,constraints);
   
    height = new JTextField(FIELD_SIZE);
    height.setActionCommand("Height");
    add(height,constraints);
   
    hypotenuse = new JTextField(FIELD_SIZE);
    hypotenuse.setEditable(false);
    add(hypotenuse,constraints);
    model.addObserver(this);
    controller = new TVController(model);
    update(model,null);
}

/**
   * Update the view with current model state.
   */
public void update (Observable model, Object arg) {
    int side;
    RightTriangle rt = (RightTriangle)model;
    side = rt.base();
    base.setText(String.valueOf(side));
    side = rt.height();
    height.setText(String.valueOf(side));
    side = rt.hypotenuse();
    hypotenuse.setText(String.valueOf(side));
}

/**
   * RightTriangle controller for a TextView.
   */
private class TVController implements ActionListener {
   
    private RightTriangle model;
   
    /**
     * Create a new controller for the specified TextView
     * of the specified RightTriangle.
     */
    public TVController (RightTriangle model) {
      this.model = model;
      TextView.this.base.addActionListener(this);
      TextView.this.height.addActionListener(this);
    }
   
    /**
     * Update the model in response to user input.
     */
    public void actionPerformed (ActionEvent e) {
      JTextField tf = (JTextField)e.getSource();
      try {
        int i = Integer.parseInt(tf.getText());
        if (i < 0) throw new NumberFormatException();
        String which = e.getActionCommand();
        if (which.equals("Base"))
          model.setBase(i);
        else
          model.setHeight(i);
      } catch (NumberFormatException ex) {
        TextView.this.update(model, null);
      }
    }
} // end of class TVController

} // end of class TextView


//ThreeViewViewer.java

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

/**
* Simple tester for RightTriangle views.
*/
public class ThreeViewViewer {

private static RTLogger logger; // global so it can be closed

public static void main (String[] args) {
    JFrame textFrame = new JFrame("Triangle View 1");
    JFrame graphicsFrame = new JFrame("Triangle View 2");
    RightTriangle model = new RightTriangle(1,1);
    TextView tview = new TextView(model);
    GraphicView gview = new GraphicView(model);
    try {
      logger = new RTLogger(model, "log.txt", textFrame);
    } catch (java.io.IOException e) {
      System.err.println("Cannot open logger: " + e.getMessage());
    }
    textFrame.getContentPane().add(tview);
    graphicsFrame.getContentPane().add(gview);
    textFrame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          e.getWindow().dispose();
          if (logger != null) logger.close();
        }
        public void windowClosed(WindowEvent e) {
          System.exit(0);
        }
      }
    );
    textFrame.pack();
    textFrame.setVisible(true);
    graphicsFrame.pack();
    graphicsFrame.setVisible(true);
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote