Using your solution from assignment 5 (given below), instead of using the built
ID: 3560291 • Letter: U
Question
Using your solution from assignment 5 (given below), instead of using the built in GUI class, JOptionPane, you are to create and use your own GUI class. In the assignment 5, you were to use both methods showInputDialog and showMessageDialog. For this assignment, your GUI class (or 2 classes if you prefer) should be able to create similar GUI objects with similar functionality as these 2 methods of JOptionPane.
Make sure you resubmit all of your classes from assignment 5 in addition to whatever new classes you create for this assignment.
Classes of assignment 5: actually solution for help.
1.
public abstract class Shape {
protected double area;
protected double perimeter;
public double getArea() {
return area;
}//getArea
public double getPerimeter() {
return perimeter;
}//getPerimeter
public abstract double calculateArea();// abstract method
public abstract void resetDimensions();//abstract method
}//class Shape
2.
import javax.swing.JOptionPane;
public class Rectangle extends Shape {
protected double length;
protected double width;
public Rectangle(int l, int w) {
if(l <= 0 || w <= 0){//if the values are not positive
throw new IllegalNegativeArgumentException("Invalid input. Parameters must be greater than 0.");
} else {// if the values are positive
this.length = l;
this.width = w;
}//else
}//constructor
public double getArea() {
return super.getArea();
}//getArea
public double getPerimeter() {
return super.getPerimeter();
}//getPerimeter
//Overide the abstract method declared in shape
public double calculateArea() {
area = length*width;
return area;
}//calculateArea
public void resetDimensions(){ //Overide the abstract method declared in shape
String input1 = JOptionPane.showInputDialog("Enter length of rectangle:");
String input2 = JOptionPane.showInputDialog("Enter width of rectangle:");
try{
int x =Integer.parseInt(input1);// convert string into integer
int y =Integer.parseInt(input2);// convert string into integer
if(x <= 0 || y <= 0){
throw new IllegalNegativeArgumentException("Invalid input, must be greater than 0.");
} else {
this.length=x;
this.width=y;
}//else
} catch(NumberFormatException nfe){
JOptionPane.showMessageDialog (null,"Number Format Exception !"+" values unchanged", "Number Format Exception", JOptionPane.ERROR_MESSAGE);
} catch(IllegalNegativeArgumentException e){
JOptionPane.showMessageDialog (null, e.toString()+" "+" values unchanged", "Illegal Negative Argument Exception", JOptionPane.ERROR_MESSAGE);
}
}//resetDimensions
}//class Rectangle
3. More similar three classes(like Rectangle extends Shape class) Circle extends Shape, class Square extends Shape and class RightTriangle extend Shape. Not given here because of similarity with Rectangle class.
4.
public class IllegalNegativeArgumentException extends IllegalArgumentException {
private String str;
public IllegalNegativeArgumentException(String s){
this.str = s;
}//constructor
public String toString(){
return str;
}//toString
}//class
5. main class:
import javax.swing.JOptionPane;
public class Assignment6 {
public static void main(String[] args){
Shape [] myShape = new Shape[10]; //create an array object of type shape with room 10
//Polymorphic Initializing super class reference with sub class object
myShape[0] = new Circle(5);
myShape[1] = new Rectangle(2, 3);
myShape[2] = new RightTriangle(3, 4, 5);
myShape[3] = new Square(5);
myShape[4] = new Circle(6);
myShape[5] = new Rectangle(3, 4);
myShape[6] = new Square(6);
myShape[7] = new RightTriangle(4, 5, 6);
myShape[8] = new Square(7);
myShape[9] = new RightTriangle(6, 7, 8);
myShape[0].resetDimensions(); //resetting dimensions of circle
myShape[1].resetDimensions(); //resetting dimensions of rectangle
//myShape[2].resetDimensions(); //resetting dimensions of right triangle
myShape[3].resetDimensions(); //resetting dimensions of square
//myShape[4].resetDimensions(); //resetting dimensions of circle
//myShape[5].resetDimensions(); //resetting dimensions of rectangle
//myShape[6].resetDimensions(); //resetting dimensions of square
myShape[7].resetDimensions(); //resetting dimensions of right triangle
//myShape[8].resetDimensions(); //resetting dimensions of square
//myShape[9].resetDimensions(); //resetting dimensions of right triangle
//initialize the variables
double area =0;
double averagearea = 0;
for(int j = 0; j < 10; j++){//Polymorphic invoking with knowing object type
double myshapearea = myShape[j].calculateArea();
System.out.println("Area of shape "+j +" is "+myshapearea );//prints area of all shapes to console(just to check whether resetDimensions method is working or not)
area = area + myshapearea;//calculate total area
averagearea = area/10;//calculate average area
}//for j
JOptionPane.showMessageDialog (null,"Average area of all shapes: "+ averagearea, "Calculated average area", JOptionPane.PLAIN_MESSAGE);
}//method main
}//class Assignment5
Explanation / Answer
// Construct an ImageIcon from an image filename
String imgFilename = "images/duke.png";
// Can use an absolute filename such as "c:/project/images/nought.gif"
ImageIcon iconDuke = new ImageIcon(imgFilename);
// OR
// Construct an ImageIcon via an image URL (in the form of file://path/filename)
ImageIcon iconDuke = null;
String imgFilename = "images/duke.png";
java.net.URL imgURL = getClass().getClassLoader().getResource(imgFilename);
// Filename always relative to the root of the project (i.e., bin)
// can access resource in a JAR file
if (imgURL != null) {
iconDuke = new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + imgFilename);
}
Using URL is more flexible as it can access resources in a JAR file, and produces an error message if the file does not exist (which results in a null URL).
Many JComponents (such as JLabel, JButton) accepts an ImageIcon in its constructor, or via the setIcon() method. For example,
ImageIcon iconDuke = null;
String imgFilename = "images/duke.gif"; // relative to project root (or bin)
URL imgURL = getClass().getClassLoader().getResource(imgFilename);
if (imgURL != null) {
iconDuke = new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + imgFilename);
}
JLabel lbl = new JLabel("The Duke", iconDuke, JLabel.CENTER);
lbl.setBackground(Color.LIGHT_GRAY);
lbl.setOpaque(true);
Container cp = getContentPane();
cp.add(lbl);
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
/** Test setting Swing's JComponents properties and appearances */
@SuppressWarnings("serial")
public class SwingJComponentSetterTest extends JFrame {
// Image path relative to the project root (i.e., bin)
private String imgCrossFilename = "images/cross.gif";
private String imgNoughtFilename = "images/nought.gif";
/** Constructor to setup the GUI */
public SwingJComponentSetterTest() {
// Prepare ImageIcons to be used with JComponents
ImageIcon iconCross = null;
ImageIcon iconNought = null;
URL imgURL = getClass().getClassLoader().getResource(imgCrossFilename);
if (imgURL != null) {
iconCross = new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + imgCrossFilename);
}
imgURL = getClass().getClassLoader().getResource(imgNoughtFilename);
if (imgURL != null) {
iconNought = new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + imgNoughtFilename);
}
Container cp = getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
// Create a JLabel with text and icon and set its appearances
JLabel label = new JLabel("JLabel", iconCross, SwingConstants.CENTER);
label.setFont(new Font(Font.DIALOG, Font.ITALIC, 14));
label.setOpaque(true); // needed for JLabel to show the background color
label.setBackground(new Color(204, 238, 241)); // light blue
label.setForeground(Color.RED); // foreground text color
label.setPreferredSize(new Dimension(120, 80));
label.setToolTipText("This is a JLabel"); // Tool tip
cp.add(label);
// Create a JButton with text and icon and set its appearances
JButton button = new JButton(); // use setter to set text and icon
button.setText("Button");
button.setIcon(iconNought);
button.setVerticalAlignment(SwingConstants.BOTTOM); // of text and icon
button.setHorizontalAlignment(SwingConstants.RIGHT); // of text and icon
button.setHorizontalTextPosition(SwingConstants.LEFT); // of text relative to icon
button.setVerticalTextPosition(SwingConstants.TOP); // of text relative to icon
button.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 15));
button.setBackground(new Color(231, 240, 248));
button.setForeground(Color.BLUE);
button.setPreferredSize(new Dimension(150, 80));
button.setToolTipText("This is a JButton");
button.setMnemonic(KeyEvent.VK_B); // can activate via Alt-B (buttons only)
cp.add(button);
// Create a JTextField with text and icon and set its appearances
JTextField textField = new JTextField("Text Field", 15);
textField.setFont(new Font(Font.DIALOG_INPUT, Font.PLAIN, 12));
textField.setForeground(Color.RED);
textField.setHorizontalAlignment(JTextField.RIGHT); // Text alignment
textField.setToolTipText("This is a JTextField");
cp.add(textField);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JComponent Test");
setLocationRelativeTo(null); // center window on the screen
setSize(500, 150); // or pack()
setVisible(true);
// Print description of the JComponents via toString()
System.out.println(label);
System.out.println(button);
System.out.println(textField);
}
/** The entry main() method */
public static void main(String[] args) {
// Run the GUI codes on Event-Dispatching thread for thread safety
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingJComponentSetterTest(); // Let the constructor do the job
}
});
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.