Java Reference
In-Depth Information
public static void
main(String [] args)
throws
Exception
{
CalculatorFrame f =
new
CalculatorFrame() ;
f . setVisible(
true
);
}
}
class
CalculatorFrame
extends
JFrame
{
JTextField text =
new
JTextField(20) ;
public
CalculatorFrame()
throws
Exception
{
setDefaultCloseOperation(JFrame.DISPOSEON CLOSE) ;
JPanel displayPanel =
new
JPanel () ;
JPanel buttonPanel =
new
JPanel () ;
JPanel bottomPanel =
new
JPanel () ;
displayPanel .add(text) ;
String [] buttonNames =
{
"7"
,
"8"
,
"9"
,
"+"
,
"4"
,
"5"
,
"6"
,
"-"
,
"1"
,
"2"
,
"3"
,
"*"
,
"0"
,
"("
,
")"
,
"/"
}
;
buttonPanel . setLayout(
new
GridLayout (4 , 4 , 5 , 5) ) ;
for
(String el : buttonNames)
{
buttonPanel .add(
new
CalculatorButton( el )) ;
JButton evaluateButton =
new
JButton(
"EVALUATE"
);
JButton clearButton =
new
JButton(
"CLEAR"
);
clearButton . addActionListener(
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
text . setText(
""
);
}
}
);
evaluateButton . addActionListener(
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
try
{
String s = (
new
ScriptEngineManager () .getEngineByName(
"
JavaScript"
) . eval(text .getText() .trim())) . toString() ;
text . setText(s) ;
}
catch
(Exception exc)
{
text . setText(
""
);
}
}
}
);
bottomPanel . add(
new
CalculatorButton(
"."
));
bottomPanel . add( clearButton ) ;
bottomPanel . add( evaluateButton) ;
add(displayPanel , BorderLayout .NORTH) ;
add(buttonPanel , BorderLayout .CENTER) ;
add(bottomPanel , BorderLayout .SOUTH) ;
setResizable(
false
);
pack() ;
}
private class
CalculatorButton
extends
JButton
{
public
CalculatorButton(String name)
{
super
(name) ;