Lab_1_1_Help/Shapes.java
Lab_1_1_Help/Shapes.java
// Lab 1 Question 1 help
import
javax
.
swing
.
*
;
public
class
Shapes
{
// execute application
public
static
void
main
(
String
[]
args
)
{
int
length
;
int
width
;
// create frame for ShapesJPanel
JFrame
frame
=
new
JFrame
(
"Drawing 2D shapes"
);
frame
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// input the length and width
length
=
Integer
.
parseInt
(
JOptionPane
.
showInputDialog
(
frame
,
"Please enter the length:"
));
width
=
Integer
.
parseInt
(
JOptionPane
.
showInputDialog
(
frame
,
"Please enter the width:"
));
// create ShapesJPanel
ShapesJPanel
shapesJPanel
=
new
ShapesJPanel
(
length
,
width
);
frame
.
add
(
shapesJPanel
);
frame
.
setSize
(
425
,
200
);
frame
.
setVisible
(
true
);
}
}
// end class Shapes
Lab_1_1_Help/ShapesJPanel.java
Lab_1_1_Help/ShapesJPanel.java
// Lab 1 Question 1 help
import
java
.
awt
.
*
;
import
java
.
awt
.
event
.
ActionEvent
;
import
java
.
awt
.
event
.
ActionListener
;
import
java
.
awt
.
geom
.
Rectangle2D
;
import
javax
.
swing
.
*
;
public
class
ShapesJPanel
extends
JPanel
{
private
int
length
;
private
int
width
;
private
JButton
exitJButton
;
//constructor to receive inputs
public
ShapesJPanel
(
int
length
,
int
width
){
this
.
length
=
length
;
this
.
width
=
width
;
exitJButton
=
new
JButton
(
"Exit"
);
exitJButton
.
addActionListener
(
new
ActionListener
()
{
@
Override
public
void
actionPerformed
(
ActionEvent
e
)
{
int
result
=
JOptionPane
.
showConfirmDialog
(
null
,
"Are you Sure?"
);
System
.
out
.
println
(
result
);
if
(
result
==
0
){
JOptionPane
.
showMessageDialog
(
null
,
"Thank you for using this program"
,
"Bye!"
,
JOptionPane
.
PLAIN_MESSAGE
);
//dispose();
System
.
exit
(
0
);}
}
}
);
this
.
setLayout
(
new
BorderLayout
());
this
.
add
(
exitJButton
,
BorderLayout
.
SOUTH
);
}
// draw shapes with Java 2D API
@
Override
public
void
paintComponent
(
Graphics
g
)
{
super
.
paintComponent
(
g
);
Graphics2D
g2d
=
(
Graphics2D
)
g
;
// cast g to Graphics2D
// draw 2D rectangle in red
g2d
.
setPaint
(
Color
.
RED
);
g2d
.
setStroke
(
new
BasicStroke
(
10.0f
));
g2d
.
draw
(
new
Rectangle2D
.
Double
(
80
,
30
,
width
,
length
));
}
}
// end class ShapesJPanel