IOapalooza5.java
Select all
/* IOapalooza5.java CIS 260 David Klick 2006-01-18 This program demonstrates how to do I/O using a basic, but complete GUI. */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class IOapalooza5 { public static void main(String[] args) { JFrame fra = new JFrame("Adding Application"); fra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = fra.getContentPane(); c.setLayout(new GridLayout(2, 2, 2, 5)); final JTextField txt = new JTextField(); txt.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { txt.setSelectionStart(0); txt.setSelectionEnd(txt.getText().length()); } public void focusLost(FocusEvent e) {} }); final JLabel lbl = new JLabel(); JButton btnAdd = new JButton("
Add
"); btnAdd.setMnemonic('a'); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double sum = 0.0, num = 0.0; String strSum = lbl.getText(); if (strSum.length() > 0) sum = Double.parseDouble(strSum); try { String strNum = txt.getText(); num = Double.parseDouble(strNum); sum += num; txt.setText(""); } catch (NumberFormatException e2) { txt.setSelectionStart(0); txt.setSelectionEnd(txt.getText().length()); } lbl.setText("" + sum); txt.requestFocusInWindow(); } }); fra.getRootPane().setDefaultButton(btnAdd); JButton btnExit = new JButton("Exit"); btnExit.setMnemonic('x'); btnExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); c.add(txt); c.add(lbl); c.add(btnAdd); c.add(btnExit); fra.setSize(200, 110); fra.setVisible(true); } }