GUI Example from Class 5/14/01
/**
*
* Thanks to Todd for the JOption heads up!
*
* @version (a version number or a date)
*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.Box;
public class GUI
{
public static void main(String [] args) {
JTextField txt = new JTextField(15);
KeyPad kpd = new KeyPad(txt);
OpPad opd = new OpPad(txt);
JPanel k = new JPanel();
k.setLayout( new BoxLayout(k, BoxLayout.X_AXIS ));
k.add(kpd);
k.add( Box.createHorizontalStrut(10) );
k.add(opd);
JPanel p = new JPanel();
p.setLayout( new BoxLayout(p, BoxLayout.Y_AXIS ));
p.add(k);
p.add( Box.createVerticalStrut(10) );
p.add(txt);
JOptionPane.showMessageDialog(null, p);
}
}
class KeyPad extends JPanel {
private JTextField expr;
private class BListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
expr.setText( expr.getText() + ((JButton)e.getSource()).getText() );
}
}
public KeyPad(JTextField txt) {
expr = txt;
char [] keys = {'7', '8', '9', '4', '5', '6', '1', '2', '3',
'(', '0', ')' };
setLayout( new GridLayout(4, 3, 4, 4) );
ActionListener action = new BListener();
for (int i = 0; i < keys.length; i++ ) {
JButton b = new JButton(new Character(keys[i]).toString());
b.addActionListener( action );
add(b);
}
}
}
class OpPad extends JPanel {
private JTextField expr;
private class BListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
expr.setText( expr.getText() + ((JButton)e.getSource()).getText() );
}
}
public OpPad(JTextField txt) {
expr = txt;
char [] keys = {'+', '-', '*', '/'};
setLayout( new GridLayout(4, 1, 4, 4) );
ActionListener action = new BListener();
for (int i = 0; i < keys.length; i++ ) {
JButton b = new JButton(new Character(keys[i]).toString());
b.addActionListener( action );
add(b);
}
}
}