import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Calculator extends JFrame implements ActionListener { private JPanel panel; private JLabel label; private JButton[] buttons; private String[] buttonLabels = {"C", "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/", "="}; public Calculator() { setBounds(100, 100, 250, 250); setTitle("Calculator"); panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new GridLayout(0, 4, 5, 5)); label = new JLabel("0"); label.setBorder(BorderFactory.createLineBorder(Color.BLACK)); label.setOpaque(true); label.setBackground(Color.WHITE); label.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 24)); label.setPreferredSize(new Dimension(0, 40)); add(label, BorderLayout.NORTH); buttons = new JButton[buttonLabels.length]; for (int i = 0; i < buttonLabels.length; i++) { JButton button = new JButton(buttonLabels[i]); button.setPreferredSize(new Dimension(0, 35)); button.addActionListener(this); buttons[i] = button; panel.add(button); } add(panel, BorderLayout.CENTER); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); String label = ""; for (int i = 0; i < buttons.length; i++) { if (source == buttons[i]) { label = buttons[i].getText(); break; } } switch (label) { case "C": this.label.setText("0"); break; case "=": String expression = this.label.getText(); Evaluator evaluator = new Evaluator(expression); this.label.setText("" + evaluator.evaluate()); break; default: if (this.label.getText().equals("0")) { this.label.setText(label); } else { this.label.setText(this.label.getText() + label); } } } public static void main(String[] args) { new Calculator(); } }Another example of using java.awt.event package and JPanel is creating a simple drawing interface. This interface allows the user to draw shapes on the JPanel. The user can select the shape (line, rectangle, ellipse) and can set the color and stroke width. The code for this example is too long to be included here, but the package library used is the same: java.awt.event and javax.swing.