CS 245 Lecture 4 – Calculator
Agenda
- specchecker example
- calculator free-for-all
TODO
- Work on preassignment 1. No 1/4 sheet.
Code
CalculatorGUI.java
package lecture0912;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CalculatorGUI {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 500);
// Panel
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(0, 3));
// Label
final JLabel numberDisplay = new JLabel();
frame.add(numberDisplay, BorderLayout.NORTH);
numberDisplay.setText("CALCULATOR");
numberDisplay.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 36));
numberDisplay.setHorizontalAlignment(JLabel.RIGHT);
JButton[] buttons = new JButton[20];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
panel.add(buttons[i]);
}
for (int i = 0; i < 10; i++) {
buttons[i].setText("" + i);
}
buttons[10].setText("+");
buttons[11].setText("-");
buttons[12].setText("*");
buttons[13].setText("/");
buttons[14].setText("=");
buttons[15].setText(".");
buttons[19].setText("Clr");
class ClearListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
numberDisplay.setText("0");
}
}
buttons[19].addActionListener(new ClearListener());
}
}
Haiku
Hypothetical
Once my code was a story
Now it’s all “What if?”
Once my code was a story
Now it’s all “What if?”