diff --git a/Ant-Common.xml b/Ant-Common.xml index 0b67c9b7..b99b32ae 100644 --- a/Ant-Common.xml +++ b/Ant-Common.xml @@ -23,8 +23,8 @@ - Running: ${chapter} @{cls} - Running: ${chapter} @{cls} + [${chapter}] Running: java @{cls} @{arguments} + [${chapter}] Running: java @{cls} @{arguments} - Finished: ${chapter} @{cls} + [${chapter}] Finished: java @{cls} @{arguments} @{msg} -------------------------------- @@ -49,8 +49,8 @@ - Running: ${chapter} @{cls} - Running: ${chapter} @{cls} + [${chapter}] Running: java @{cls} @{arguments} + [${chapter}] Running: java @{cls} @{arguments} - Finished: ${chapter} @{cls} + [${chapter}] Finished: java @{cls} @{arguments} @{msg} -------------------------------- diff --git a/arrays/GeneratorsTest.java b/arrays/GeneratorsTest.java index 2ff4848a..fa59de7f 100644 --- a/arrays/GeneratorsTest.java +++ b/arrays/GeneratorsTest.java @@ -11,7 +11,8 @@ public class GeneratorsTest { for(int i = 0; i < size; i++) System.out.printf(g.next() + " "); System.out.println(); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/concurrency/ActiveObjectDemo.java b/concurrency/ActiveObjectDemo.java index cc52e0e5..b783b3c9 100644 --- a/concurrency/ActiveObjectDemo.java +++ b/concurrency/ActiveObjectDemo.java @@ -52,7 +52,8 @@ public class ActiveObjectDemo { if(f.isDone()) { try { print(f.get()); - } catch(Exception e) { + } catch(InterruptedException | + ExecutionException e) { throw new RuntimeException(e); } results.remove(f); diff --git a/concurrency/GreenhouseScheduler.java b/concurrency/GreenhouseScheduler.java index 3aefcf37..e7b40819 100644 --- a/concurrency/GreenhouseScheduler.java +++ b/concurrency/GreenhouseScheduler.java @@ -137,12 +137,10 @@ public class GreenhouseScheduler { if(rand.nextInt(5) == 4) tempDirection = -tempDirection; // Store previous value: - lastTemp = lastTemp + - tempDirection * (1.0f + rand.nextFloat()); + lastTemp += tempDirection * (1.0f + rand.nextFloat()); if(rand.nextInt(5) == 4) humidityDirection = -humidityDirection; - lastHumidity = lastHumidity + - humidityDirection * rand.nextFloat(); + lastHumidity += humidityDirection * rand.nextFloat(); // Calendar must be cloned, otherwise all // DataPoints hold references to the same lastTime. // For a basic object like Calendar, clone() is OK. diff --git a/concurrency/InterruptingIdiom.java b/concurrency/InterruptingIdiom.java index 7347144f..115d327a 100644 --- a/concurrency/InterruptingIdiom.java +++ b/concurrency/InterruptingIdiom.java @@ -35,7 +35,7 @@ class Blocked3 implements Runnable { print("Calculating"); // A time-consuming, non-blocking operation: for(int i = 1; i < 2500000; i++) - d = d + (Math.PI + Math.E) / d; + d += (Math.PI + Math.E) / d; print("Finished time-consuming operation"); } finally { n2.cleanup(); diff --git a/concurrency/Pool.java b/concurrency/Pool.java index bd9b52db..3d3c400b 100644 --- a/concurrency/Pool.java +++ b/concurrency/Pool.java @@ -18,7 +18,8 @@ public class Pool { try { // Assumes a default constructor: items.add(classObject.newInstance()); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/concurrency/ResponsiveUI.java b/concurrency/ResponsiveUI.java index 5f03b380..70ea0d4f 100644 --- a/concurrency/ResponsiveUI.java +++ b/concurrency/ResponsiveUI.java @@ -6,7 +6,7 @@ class UnresponsiveUI { private volatile double d = 1; public UnresponsiveUI() throws Exception { while(d > 0) - d = d + (Math.PI + Math.E) / d; + d += (Math.PI + Math.E) / d; System.in.read(); // Never gets here } } @@ -20,7 +20,7 @@ public class ResponsiveUI extends Thread { @Override public void run() { while(true) { - d = d + (Math.PI + Math.E) / d; + d += (Math.PI + Math.E) / d; } } public static void main(String[] args) throws Exception { diff --git a/concurrency/SynchronizationComparisons.java b/concurrency/SynchronizationComparisons.java index 693089db..7fe0d0d9 100644 --- a/concurrency/SynchronizationComparisons.java +++ b/concurrency/SynchronizationComparisons.java @@ -35,7 +35,8 @@ abstract class Accumulator { accumulate(); try { barrier.await(); - } catch(Exception e) { + } catch(InterruptedException | + BrokenBarrierException e) { throw new RuntimeException(e); } } @@ -48,7 +49,8 @@ abstract class Accumulator { value = read(); try { barrier.await(); - } catch(Exception e) { + } catch(InterruptedException | + BrokenBarrierException e) { throw new RuntimeException(e); } } @@ -61,7 +63,8 @@ abstract class Accumulator { } try { barrier.await(); - } catch(Exception e) { + } catch(InterruptedException | + BrokenBarrierException e) { throw new RuntimeException(e); } duration = System.nanoTime() - start; diff --git a/containers/CountedString.java b/containers/CountedString.java index 18c71f2a..d145a05d 100644 --- a/containers/CountedString.java +++ b/containers/CountedString.java @@ -44,7 +44,7 @@ public class CountedString { CountedString[] cs = new CountedString[5]; for(int i = 0; i < cs.length; i++) { cs[i] = new CountedString("hi"); - map.put(cs[i], i); // Autobox int -> Integer + map.put(cs[i], i); // Autobox int to Integer } print(map); for(CountedString cstring : cs) { diff --git a/containers/TypesForSets.java b/containers/TypesForSets.java index 2ecb947a..7ac40b2a 100644 --- a/containers/TypesForSets.java +++ b/containers/TypesForSets.java @@ -1,5 +1,6 @@ //: containers/TypesForSets.java // Methods necessary to put your own type in a Set. +import java.lang.reflect.InvocationTargetException; import java.util.*; class SetType { @@ -34,7 +35,12 @@ public class TypesForSets { for(int i = 0; i < 10; i++) set.add( type.getConstructor(int.class).newInstance(i)); - } catch(Exception e) { + } catch(NoSuchMethodException | + SecurityException | + InstantiationException | + IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { throw new RuntimeException(e); } return set; diff --git a/control/StringSwitch.java b/control/StringSwitch.java index 1cb5fab8..d548d496 100644 --- a/control/StringSwitch.java +++ b/control/StringSwitch.java @@ -5,13 +5,13 @@ public class StringSwitch { public static void main(String[] args) { String color = "red"; // Old way: using if-then - if(color == "red") { + if("red".equals(color)) { print("RED"); - } else if(color == "green") { + } else if("green".equals(color)) { print("GREEN"); - } else if(color == "blue") { + } else if("blue".equals(color)) { print("BLUE"); - } else if(color == "yellow") { + } else if("yellow".equals(color)) { print("YELLOW"); } else { print("Unknown"); diff --git a/enumerated/EnumMaps.java b/enumerated/EnumMaps.java index 367ca93b..60b3434b 100644 --- a/enumerated/EnumMaps.java +++ b/enumerated/EnumMaps.java @@ -11,12 +11,8 @@ public class EnumMaps { public static void main(String[] args) { EnumMap em = new EnumMap<>(AlarmPoints.class); - em.put(KITCHEN, (Command) () -> { - print("Kitchen fire!"); - }); - em.put(BATHROOM, (Command) () -> { - print("Bathroom alert!"); - }); + em.put(KITCHEN, () -> print("Kitchen fire!")); + em.put(BATHROOM, () -> print("Bathroom alert!")); for(Map.Entry e : em.entrySet()) { printnb(e.getKey() + ": "); e.getValue().action(); diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index 5a73d49a..acb1a842 100644 --- a/exceptions/DynamicFields.java +++ b/exceptions/DynamicFields.java @@ -93,9 +93,8 @@ public class DynamicFields { print("df: " + df); print("df.getField(\"d\") : " + df.getField("d")); Object field = df.setField("d", null); // Exception - } catch(NoSuchFieldException e) { - e.printStackTrace(System.out); - } catch(DynamicFieldsException e) { + } catch(NoSuchFieldException | + DynamicFieldsException e) { e.printStackTrace(System.out); } } diff --git a/exceptions/LostMessage.java b/exceptions/LostMessage.java index 93f623ce..152fb002 100644 --- a/exceptions/LostMessage.java +++ b/exceptions/LostMessage.java @@ -30,7 +30,8 @@ public class LostMessage { } finally { lm.dispose(); } - } catch(Exception e) { + } catch(VeryImportantException | + HoHumException e) { System.out.println(e); } } diff --git a/exceptions/TurnOffChecking.java b/exceptions/TurnOffChecking.java index 460f4ac4..47085648 100644 --- a/exceptions/TurnOffChecking.java +++ b/exceptions/TurnOffChecking.java @@ -12,7 +12,8 @@ class WrapCheckedException { case 2: throw new RuntimeException("Where am I?"); default: return; } - } catch(Exception e) { // Adapt to unchecked: + } catch(IOException | RuntimeException e) { + // Adapt to unchecked: throw new RuntimeException(e); } } diff --git a/generics/Apply.java b/generics/Apply.java index def46a5a..3ae9d630 100644 --- a/generics/Apply.java +++ b/generics/Apply.java @@ -10,7 +10,9 @@ public class Apply { try { for(T t: seq) f.invoke(t, args); - } catch(Exception e) { + } catch(IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { // Failures are programmer errors throw new RuntimeException(e); } @@ -32,7 +34,8 @@ class FilledList extends ArrayList { for(int i = 0; i < size; i++) // Assumes default constructor: add(type.newInstance()); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/generics/Fill.java b/generics/Fill.java index 1fca1ba9..dcd84da7 100644 --- a/generics/Fill.java +++ b/generics/Fill.java @@ -14,7 +14,8 @@ public class Fill { // Assumes default constructor: try { collection.add(classToken.newInstance()); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/generics/Fill2.java b/generics/Fill2.java index cbac1482..4c7c831f 100644 --- a/generics/Fill2.java +++ b/generics/Fill2.java @@ -15,7 +15,8 @@ public class Fill2 { for(int i = 0; i < size; i++) try { addable.add(classToken.newInstance()); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/generics/GenericArray2.java b/generics/GenericArray2.java index b88afaf8..792f4259 100644 --- a/generics/GenericArray2.java +++ b/generics/GenericArray2.java @@ -24,7 +24,9 @@ public class GenericArray2 { System.out.println(); try { Integer[] ia = gai.rep(); - } catch(Exception e) { System.out.println(e); } + } catch(Exception e) { + System.out.println(e); + } } } /* Output: (Sample) 0 1 2 3 4 5 6 7 8 9 diff --git a/generics/InstantiateGenericType.java b/generics/InstantiateGenericType.java index c00daf5e..7b9f224f 100644 --- a/generics/InstantiateGenericType.java +++ b/generics/InstantiateGenericType.java @@ -6,7 +6,8 @@ class ClassAsFactory { public ClassAsFactory(Class kind) { try { x = kind.newInstance(); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/generics/LatentReflection.java b/generics/LatentReflection.java index 3586702e..f359c0b2 100644 --- a/generics/LatentReflection.java +++ b/generics/LatentReflection.java @@ -35,7 +35,10 @@ class CommunicateReflectively { } catch(NoSuchMethodException e) { print(speaker + " cannot sit"); } - } catch(Exception e) { + } catch(SecurityException | + IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { throw new RuntimeException(speaker.toString(), e); } } diff --git a/generics/coffee/CoffeeGenerator.java b/generics/coffee/CoffeeGenerator.java index 43869c1a..c4db7239 100644 --- a/generics/coffee/CoffeeGenerator.java +++ b/generics/coffee/CoffeeGenerator.java @@ -19,7 +19,8 @@ implements Generator, Iterable { return (Coffee) types[rand.nextInt(types.length)].newInstance(); // Report programmer errors at run time: - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/gui/Button2b.java b/gui/Button2b.java index 2fbe07df..a1e7612c 100644 --- a/gui/Button2b.java +++ b/gui/Button2b.java @@ -10,7 +10,7 @@ public class Button2b extends JFrame { b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); private JTextField txt = new JTextField(10); - private ActionListener bl = (ActionEvent e) -> { + private ActionListener bl = e -> { String name1 = ((JButton)e.getSource()).getText(); txt.setText(name1); }; diff --git a/gui/ButtonGroups.java b/gui/ButtonGroups.java index 0f94d92f..94140c83 100644 --- a/gui/ButtonGroups.java +++ b/gui/ButtonGroups.java @@ -27,7 +27,12 @@ public class ButtonGroups extends JFrame { kind.getConstructor(String.class); // Create a new object: ab = (AbstractButton)ctor.newInstance(id); - } catch(Exception ex) { + } catch(NoSuchMethodException | + SecurityException | + InstantiationException | + IllegalAccessException | + IllegalArgumentException | + InvocationTargetException ex) { System.err.println("can't create " + kind); } bg.add(ab); diff --git a/gui/CheckBoxes.java b/gui/CheckBoxes.java index b56d9518..bc129bc1 100644 --- a/gui/CheckBoxes.java +++ b/gui/CheckBoxes.java @@ -12,15 +12,9 @@ public class CheckBoxes extends JFrame { cb2 = new JCheckBox("Check Box 2"), cb3 = new JCheckBox("Check Box 3"); public CheckBoxes() { - cb1.addActionListener((ActionEvent e) -> { - trace("1", cb1); - }); - cb2.addActionListener((ActionEvent e) -> { - trace("2", cb2); - }); - cb3.addActionListener((ActionEvent e) -> { - trace("3", cb3); - }); + cb1.addActionListener(e -> trace("1", cb1)); + cb2.addActionListener(e -> trace("2", cb2)); + cb3.addActionListener(e -> trace("3", cb3)); setLayout(new FlowLayout()); add(new JScrollPane(t)); add(cb1); diff --git a/gui/ComboBoxes.java b/gui/ComboBoxes.java index 99f34d1b..74d94f0d 100644 --- a/gui/ComboBoxes.java +++ b/gui/ComboBoxes.java @@ -11,18 +11,18 @@ public class ComboBoxes extends JFrame { "Somnescent", "Timorous", "Florid", "Putrescent" }; private JTextField t = new JTextField(15); - private JComboBox c = new JComboBox(); + private JComboBox c = new JComboBox<>(); private JButton b = new JButton("Add items"); private int count = 0; public ComboBoxes() { for(int i = 0; i < 4; i++) c.addItem(description[count++]); t.setEditable(false); - b.addActionListener((ActionEvent e) -> { + b.addActionListener(e -> { if(count < description.length) c.addItem(description[count++]); }); - c.addActionListener((ActionEvent e) -> { + c.addActionListener(e -> { t.setText("index: "+ c.getSelectedIndex() + " " + ((JComboBox)e.getSource()).getSelectedItem()); }); diff --git a/gui/Dialogs.java b/gui/Dialogs.java index 361e0aa8..e07a705e 100644 --- a/gui/Dialogs.java +++ b/gui/Dialogs.java @@ -11,9 +11,8 @@ class MyDialog extends JDialog { setLayout(new FlowLayout()); add(new JLabel("Here is my dialog")); JButton ok = new JButton("OK"); - ok.addActionListener((ActionEvent e) -> { - dispose(); // Closes the dialog - }); + ok.addActionListener(e -> + dispose()); // Closes the dialog add(ok); setSize(150,125); } @@ -23,9 +22,7 @@ public class Dialogs extends JFrame { private JButton b1 = new JButton("Dialog Box"); private MyDialog dlg = new MyDialog(null); public Dialogs() { - b1.addActionListener((ActionEvent e) -> { - dlg.setVisible(true); - }); + b1.addActionListener(e -> dlg.setVisible(true)); add(b1); } public static void main(String[] args) { diff --git a/gui/Faces.java b/gui/Faces.java index e558d9ff..e328c9df 100644 --- a/gui/Faces.java +++ b/gui/Faces.java @@ -19,7 +19,7 @@ public class Faces extends JFrame { }; jb = new JButton("JButton", faces[3]); setLayout(new FlowLayout()); - jb.addActionListener((ActionEvent e) -> { + jb.addActionListener(e -> { if(mad) { jb.setIcon(faces[3]); mad = false; @@ -36,7 +36,7 @@ public class Faces extends JFrame { jb.setDisabledIcon(faces[4]); jb.setToolTipText("Yow!"); add(jb); - jb2.addActionListener((ActionEvent e) -> { + jb2.addActionListener(e -> { if(jb.isEnabled()) { jb.setEnabled(false); jb2.setText("Enable"); diff --git a/gui/HTMLButton.java b/gui/HTMLButton.java index f9b4fb47..2810321d 100644 --- a/gui/HTMLButton.java +++ b/gui/HTMLButton.java @@ -10,7 +10,7 @@ public class HTMLButton extends JFrame { "" + "
Hello!
Press me now!"); public HTMLButton() { - b.addActionListener((ActionEvent e) -> { + b.addActionListener(e -> { add(new JLabel("" + "Kapow!")); // Force a re-layout to include the new label: diff --git a/gui/InterruptableLongRunningCallable.java b/gui/InterruptableLongRunningCallable.java index b0ece653..8a2119ba 100644 --- a/gui/InterruptableLongRunningCallable.java +++ b/gui/InterruptableLongRunningCallable.java @@ -25,16 +25,16 @@ InterruptableLongRunningCallable extends JFrame { private TaskManager manager = new TaskManager<>(); public InterruptableLongRunningCallable() { - b1.addActionListener((ActionEvent e) -> { + b1.addActionListener(e -> { CallableTask task = new CallableTask(); manager.add(task); System.out.println(task + " added to the queue"); }); - b2.addActionListener((ActionEvent e) -> { + b2.addActionListener(e -> { for(String result : manager.purge()) System.out.println(result); }); - b3.addActionListener((ActionEvent e) -> { + b3.addActionListener(e -> { // Sample call to a Task method: for(TaskItem tt : manager) tt.task.id(); // No cast required diff --git a/gui/InterruptableLongRunningTask.java b/gui/InterruptableLongRunningTask.java index 8e03218e..8a99db58 100644 --- a/gui/InterruptableLongRunningTask.java +++ b/gui/InterruptableLongRunningTask.java @@ -32,12 +32,12 @@ public class InterruptableLongRunningTask extends JFrame { ExecutorService executor = Executors.newSingleThreadExecutor(); public InterruptableLongRunningTask() { - b1.addActionListener((ActionEvent e) -> { + b1.addActionListener(e -> { Task task = new Task(); executor.execute(task); System.out.println(task + " added to the queue"); }); - b2.addActionListener((ActionEvent e) -> { + b2.addActionListener(e -> { executor.shutdownNow(); // Heavy-handed }); setLayout(new FlowLayout()); diff --git a/gui/List.java b/gui/List.java index a789411d..fa34f01e 100644 --- a/gui/List.java +++ b/gui/List.java @@ -13,12 +13,13 @@ public class List extends JFrame { "Praline Cream", "Mud Pie" }; private int count = 0; - private DefaultListModel lItems = new DefaultListModel(); - private JList lst = new JList(lItems); + private DefaultListModel lItems = + new DefaultListModel<>(); + private JList lst = new JList<>(lItems); private JTextArea t = new JTextArea(flavors.length, 20); private JButton b = new JButton("Add Item"); - private ActionListener bl = (ActionEvent e) -> { + private ActionListener bl = e -> { if(count < flavors.length) { lItems.add(0, flavors[count++]); } else { @@ -27,12 +28,11 @@ public class List extends JFrame { b.setEnabled(false); } }; - private ListSelectionListener ll = - (ListSelectionEvent e) -> { - if(e.getValueIsAdjusting()) return; - t.setText(""); - for(Object item : lst.getSelectedValues()) - t.append(item + "\n"); + private ListSelectionListener ll = e -> { + if(e.getValueIsAdjusting()) return; + t.setText(""); + for(Object item : lst.getSelectedValuesList()) + t.append(item + "\n"); }; public List() { t.setEditable(false); diff --git a/gui/LongRunningTask.java b/gui/LongRunningTask.java index c6766352..62199de2 100644 --- a/gui/LongRunningTask.java +++ b/gui/LongRunningTask.java @@ -11,16 +11,16 @@ public class LongRunningTask extends JFrame { b1 = new JButton("Start Long Running Task"), b2 = new JButton("End Long Running Task"); public LongRunningTask() { - b1.addActionListener((ActionEvent evt) -> { + b1.addActionListener(e -> { try { TimeUnit.SECONDS.sleep(3); - } catch(InterruptedException e) { + } catch(InterruptedException ex) { System.out.println("Task interrupted"); return; } System.out.println("Task completed"); }); - b2.addActionListener((ActionEvent evt) -> { + b2.addActionListener(e -> { // Interrupt yourself? Thread.currentThread().interrupt(); }); diff --git a/gui/LookAndFeel.java b/gui/LookAndFeel.java index e4f93e0a..da684e65 100644 --- a/gui/LookAndFeel.java +++ b/gui/LookAndFeel.java @@ -14,8 +14,8 @@ public class LookAndFeel extends JFrame { new JLabel("JLabel"), new JCheckBox("JCheckBox"), new JRadioButton("Radio"), - new JComboBox(choices), - new JList(choices), + new JComboBox(choices), + new JList(choices), }; public LookAndFeel() { super("Look And Feel"); @@ -35,7 +35,10 @@ public class LookAndFeel extends JFrame { try { UIManager.setLookAndFeel(UIManager. getCrossPlatformLookAndFeelClassName()); - } catch(Exception e) { + } catch(ClassNotFoundException | + InstantiationException | + IllegalAccessException | + UnsupportedLookAndFeelException e) { e.printStackTrace(); } break; @@ -43,7 +46,10 @@ public class LookAndFeel extends JFrame { try { UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName()); - } catch(Exception e) { + } catch(ClassNotFoundException | + InstantiationException | + IllegalAccessException | + UnsupportedLookAndFeelException e) { e.printStackTrace(); } break; @@ -51,7 +57,10 @@ public class LookAndFeel extends JFrame { try { UIManager.setLookAndFeel("com.sun.java."+ "swing.plaf.motif.MotifLookAndFeel"); - } catch(Exception e) { + } catch(ClassNotFoundException | + InstantiationException | + IllegalAccessException | + UnsupportedLookAndFeelException e) { e.printStackTrace(); } break; diff --git a/gui/MessageBoxes.java b/gui/MessageBoxes.java index 0e378b0f..b75a5627 100644 --- a/gui/MessageBoxes.java +++ b/gui/MessageBoxes.java @@ -12,7 +12,7 @@ public class MessageBoxes extends JFrame { new JButton("3 Vals") }; private JTextField txt = new JTextField(15); - private ActionListener al = (ActionEvent e) -> { + private ActionListener al = e -> { String id = ((JButton)e.getSource()).getText(); switch (id) { case "Alert": diff --git a/gui/MonitoredLongRunningCallable.java b/gui/MonitoredLongRunningCallable.java index d31f7560..7e5c97fc 100644 --- a/gui/MonitoredLongRunningCallable.java +++ b/gui/MonitoredLongRunningCallable.java @@ -51,7 +51,7 @@ public class MonitoredLongRunningCallable extends JFrame { private TaskManager manager = new TaskManager<>(); public MonitoredLongRunningCallable() { - b1.addActionListener((ActionEvent e) -> { + b1.addActionListener(e -> { MonitoredCallable task = new MonitoredCallable( new ProgressMonitor( MonitoredLongRunningCallable.this, @@ -60,11 +60,11 @@ public class MonitoredLongRunningCallable extends JFrame { manager.add(task); System.out.println(task + " added to the queue"); }); - b2.addActionListener((ActionEvent e) -> { + b2.addActionListener(e -> { for(String result : manager.purge()) System.out.println(result); }); - b3.addActionListener((ActionEvent e) -> { + b3.addActionListener(e -> { for(String result : manager.getResults()) System.out.println(result); }); diff --git a/gui/Popup.java b/gui/Popup.java index 0ab455be..87fc3aa0 100644 --- a/gui/Popup.java +++ b/gui/Popup.java @@ -11,9 +11,8 @@ public class Popup extends JFrame { public Popup() { setLayout(new FlowLayout()); add(t); - ActionListener al = (ActionEvent e) -> { + ActionListener al = e -> t.setText(((JMenuItem)e.getSource()).getText()); - }; JMenuItem m = new JMenuItem("Hither"); m.addActionListener(al); popup.add(m); diff --git a/gui/Progress.java b/gui/Progress.java index 9b717842..2352f568 100644 --- a/gui/Progress.java +++ b/gui/Progress.java @@ -24,9 +24,8 @@ public class Progress extends JFrame { sb.setBorder(new TitledBorder("Slide Me")); pb.setModel(sb.getModel()); // Share model add(sb); - sb.addChangeListener((ChangeEvent e) -> { - pm.setProgress(sb.getValue()); - }); + sb.addChangeListener(e -> + pm.setProgress(sb.getValue())); } public static void main(String[] args) { run(new Progress(), 300, 200); diff --git a/gui/RadioButtons.java b/gui/RadioButtons.java index 90798932..75d172f5 100644 --- a/gui/RadioButtons.java +++ b/gui/RadioButtons.java @@ -12,10 +12,9 @@ public class RadioButtons extends JFrame { rb1 = new JRadioButton("one", false), rb2 = new JRadioButton("two", false), rb3 = new JRadioButton("three", false); - private ActionListener al = (ActionEvent e) -> { + private ActionListener al = e -> t.setText("Radio button " + ((JRadioButton)e.getSource()).getText()); - }; public RadioButtons() { rb1.addActionListener(al); rb2.addActionListener(al); diff --git a/gui/SimpleMenus.java b/gui/SimpleMenus.java index a779f4e2..1f7870fe 100644 --- a/gui/SimpleMenus.java +++ b/gui/SimpleMenus.java @@ -6,9 +6,8 @@ import static net.mindview.util.SwingConsole.*; public class SimpleMenus extends JFrame { private JTextField t = new JTextField(15); - private ActionListener al = (ActionEvent e) -> { + private ActionListener al = e -> t.setText(((JMenuItem)e.getSource()).getText()); - }; private JMenu[] menus = { new JMenu("Winken"), new JMenu("Blinken"), new JMenu("Nod") diff --git a/gui/SubmitLabelManipulationTask.java b/gui/SubmitLabelManipulationTask.java index db76bde4..1bc7258b 100644 --- a/gui/SubmitLabelManipulationTask.java +++ b/gui/SubmitLabelManipulationTask.java @@ -11,8 +11,7 @@ public class SubmitLabelManipulationTask { frame.setSize(300, 100); frame.setVisible(true); TimeUnit.SECONDS.sleep(1); - SwingUtilities.invokeLater(() -> { - label.setText("Hey! This is Different!"); - }); + SwingUtilities.invokeLater(() -> + label.setText("Hey! This is Different!")); } } ///:~ diff --git a/gui/SubmitSwingProgram.java b/gui/SubmitSwingProgram.java index 85f71459..377602b8 100644 --- a/gui/SubmitSwingProgram.java +++ b/gui/SubmitSwingProgram.java @@ -14,12 +14,10 @@ public class SubmitSwingProgram extends JFrame { } static SubmitSwingProgram ssp; public static void main(String[] args) throws Exception { - SwingUtilities.invokeLater(() -> { - ssp = new SubmitSwingProgram(); - }); + SwingUtilities.invokeLater(() -> + ssp = new SubmitSwingProgram()); TimeUnit.SECONDS.sleep(1); - SwingUtilities.invokeLater(() -> { - ssp.label.setText("Hey! This is Different!"); - }); + SwingUtilities.invokeLater(() -> + ssp.label.setText("Hey! This is Different!")); } } ///:~ diff --git a/gui/TabbedPane1.java b/gui/TabbedPane1.java index 6000c0e8..ca44cb42 100644 --- a/gui/TabbedPane1.java +++ b/gui/TabbedPane1.java @@ -18,10 +18,9 @@ public class TabbedPane1 extends JFrame { for(String flavor : flavors) tabs.addTab(flavors[i], new JButton("Tabbed pane " + i++)); - tabs.addChangeListener((ChangeEvent e) -> { + tabs.addChangeListener(e -> txt.setText("Tab selected: " + - tabs.getSelectedIndex()); - }); + tabs.getSelectedIndex())); add(BorderLayout.SOUTH, txt); add(tabs); } diff --git a/gui/TextArea.java b/gui/TextArea.java index c2bb3142..15c228da 100644 --- a/gui/TextArea.java +++ b/gui/TextArea.java @@ -16,13 +16,11 @@ public class TextArea extends JFrame { public TextArea() { // Use up all the data: m.putAll(Countries.capitals()); - b.addActionListener((ActionEvent e) -> { + b.addActionListener(e -> { for(Map.Entry me : m.entrySet()) t.append(me.getKey() + ": "+ me.getValue()+"\n"); }); - c.addActionListener((ActionEvent e) -> { - t.setText(""); - }); + c.addActionListener(e -> t.setText("")); setLayout(new FlowLayout()); add(new JScrollPane(t)); add(b); diff --git a/gui/TextPane.java b/gui/TextPane.java index 639106c5..a8564275 100644 --- a/gui/TextPane.java +++ b/gui/TextPane.java @@ -12,7 +12,7 @@ public class TextPane extends JFrame { private static Generator sg = new RandomGenerator.String(7); public TextPane() { - b.addActionListener((ActionEvent e) -> { + b.addActionListener(e -> { for(int i = 1; i < 10; i++) tp.setText(tp.getText() + sg.next() + "\n"); }); diff --git a/initialization/ArraysOfPrimitives.java b/initialization/ArraysOfPrimitives.java index dedb1b0f..254707ca 100644 --- a/initialization/ArraysOfPrimitives.java +++ b/initialization/ArraysOfPrimitives.java @@ -7,7 +7,7 @@ public class ArraysOfPrimitives { int[] a2; a2 = a1; for(int i = 0; i < a2.length; i++) - a2[i] = a2[i] + 1; + a2[i] += 1; for(int i = 0; i < a1.length; i++) print("a1[" + i + "] = " + a1[i]); } diff --git a/innerclasses/LambdaExpressions.java b/innerclasses/LambdaExpressions.java index 272297c2..52561962 100644 --- a/innerclasses/LambdaExpressions.java +++ b/innerclasses/LambdaExpressions.java @@ -1,15 +1,41 @@ //: innerclasses/LambdaExpressions.java +import static net.mindview.util.Print.*; interface Description { String brief(); } +interface Body { + String detailed(String head); +} + +interface Multi { + String twoArg(String head, Double d); +} + public class LambdaExpressions { Description desc = new Description() { @Override - public String brief() { - return "Short info"; + public String brief() { + return "Short info"; } }; - Description desc2 = () -> "Short info"; + Description desc2 = () -> "Short info"; + + Body bod = (h) -> h + " More details"; + Body bod2 = h -> h + " No Parens!"; + + Multi mult = (h, n) -> h + n; + // Parens are required with multiple args: + // Multi mult2 = h, n -> h + n; // Nope + + public static void main(String[] args) { + LambdaExpressions le = + new LambdaExpressions(); + print(le.desc.brief()); + print(le.desc2.brief()); + print(le.bod.detailed("Hi!")); + print(le.bod2.detailed("Oh!")); + print(le.mult.twoArg("Pi! ", 3.14159)); + } } ///:~ diff --git a/innerclasses/build.xml b/innerclasses/build.xml index f16a599b..9ab4a805 100644 --- a/innerclasses/build.xml +++ b/innerclasses/build.xml @@ -17,6 +17,7 @@ + diff --git a/net/mindview/atunit/AtUnit.java b/net/mindview/atunit/AtUnit.java index 7f24d98a..022c33c3 100644 --- a/net/mindview/atunit/AtUnit.java +++ b/net/mindview/atunit/AtUnit.java @@ -34,7 +34,7 @@ public class AtUnit implements ProcessFiles.Strategy { if(!cName.contains(".")) return; // Ignore unpackaged classes testClass = Class.forName(cName); - } catch(Exception e) { + } catch(IOException | ClassNotFoundException e) { throw new RuntimeException(e); } TestMethods testMethods = new TestMethods(); @@ -86,7 +86,9 @@ public class AtUnit implements ProcessFiles.Strategy { } if(cleanup != null) cleanup.invoke(testObject, testObject); - } catch(Exception e) { + } catch(IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { throw new RuntimeException(e); } } @@ -137,14 +139,17 @@ public class AtUnit implements ProcessFiles.Strategy { if(creator != null) { try { return creator.invoke(testClass); - } catch(Exception e) { + } catch(IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { throw new RuntimeException("Couldn't run " + "@TestObject (creator) method."); } } else { // Use the default constructor: try { return testClass.newInstance(); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException("Couldn't create a " + "test object. Try using a @TestObject method."); } diff --git a/net/mindview/atunit/ClassNameFinder.java b/net/mindview/atunit/ClassNameFinder.java index 9b7bed24..baf76bb7 100644 --- a/net/mindview/atunit/ClassNameFinder.java +++ b/net/mindview/atunit/ClassNameFinder.java @@ -58,7 +58,7 @@ public class ClassNameFinder { int super_class = data.readShort(); return classNameTable.get( offsetTable.get(this_class)).replace('/', '.'); - } catch(Exception e) { + } catch(IOException | RuntimeException e) { throw new RuntimeException(e); } } diff --git a/net/mindview/util/BasicGenerator.java b/net/mindview/util/BasicGenerator.java index 62ed83c9..089eedd4 100644 --- a/net/mindview/util/BasicGenerator.java +++ b/net/mindview/util/BasicGenerator.java @@ -11,7 +11,8 @@ public class BasicGenerator implements Generator { try { // Assumes type is a public class: return type.newInstance(); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/net/mindview/util/ProcessFiles.java b/net/mindview/util/ProcessFiles.java index dc7faa9e..72443803 100644 --- a/net/mindview/util/ProcessFiles.java +++ b/net/mindview/util/ProcessFiles.java @@ -41,8 +41,7 @@ public class ProcessFiles { } // Demonstration of how to use it: public static void main(String[] args) { - new ProcessFiles((File file) -> { - System.out.println(file); - }, "java").start(args); + new ProcessFiles(file -> System.out.println(file), + "java").start(args); } } /* (Execute to see output) *///:~ diff --git a/net/mindview/util/TaskManager.java b/net/mindview/util/TaskManager.java index 2d5cd8e5..1af82bd0 100644 --- a/net/mindview/util/TaskManager.java +++ b/net/mindview/util/TaskManager.java @@ -19,7 +19,8 @@ extends ArrayList> { if(item.future.isDone()) { try { results.add(item.future.get()); - } catch(Exception e) { + } catch(InterruptedException | + ExecutionException e) { throw new RuntimeException(e); } items.remove(); diff --git a/network/ChatterClient.java b/network/ChatterClient.java index 047b923b..a6d3e8ae 100644 --- a/network/ChatterClient.java +++ b/network/ChatterClient.java @@ -2,7 +2,6 @@ // {TimeOutDuringTesting} // Tests the ChatterServer by starting multiple // clients, each of which sends datagrams. -import java.lang.Thread; import java.net.*; import java.io.*; diff --git a/network/MultiSimpleClient.java b/network/MultiSimpleClient.java index 3328decf..5d6b4568 100644 --- a/network/MultiSimpleClient.java +++ b/network/MultiSimpleClient.java @@ -79,7 +79,7 @@ public class MultiSimpleClient { if(SimpleClientThread.threadCount() < MAX_THREADS) new SimpleClientThread(addr); - Thread.currentThread().sleep(100); + Thread.sleep(100); } } } ///:~ diff --git a/patterns/factory/ShapeFactory1.java b/patterns/factory/ShapeFactory1.java index dd7499aa..c6a6762b 100644 --- a/patterns/factory/ShapeFactory1.java +++ b/patterns/factory/ShapeFactory1.java @@ -14,8 +14,8 @@ abstract class Shape { public abstract void erase(); static Shape factory(String type) throws BadShapeCreation { - if(type == "Circle") return new Circle(); - if(type == "Square") return new Square(); + if("Circle".equals(type)) return new Circle(); + if("Square".equals(type)) return new Square(); throw new BadShapeCreation(type); } } diff --git a/patterns/trash/ParseTrash.java b/patterns/trash/ParseTrash.java index eaf914ef..943c5275 100644 --- a/patterns/trash/ParseTrash.java +++ b/patterns/trash/ParseTrash.java @@ -27,7 +27,9 @@ public class ParseTrash { } } catch(IOException e) { e.printStackTrace(); - } catch(Exception e) { + } catch(NumberFormatException | + Trash.PrototypeNotFoundException | + Trash.CannotCreateTrashException e) { e.printStackTrace(); } } diff --git a/patterns/trash/Trash.java b/patterns/trash/Trash.java index 0db06d3d..ee61a2ef 100644 --- a/patterns/trash/Trash.java +++ b/patterns/trash/Trash.java @@ -54,7 +54,12 @@ public abstract class Trash { // new object: return (Trash)ctor.newInstance( new Object[]{info.data}); - } catch(Exception ex) { + } catch(NoSuchMethodException | + SecurityException | + InstantiationException | + IllegalAccessException | + IllegalArgumentException | + InvocationTargetException ex) { ex.printStackTrace(); throw new CannotCreateTrashException(); } diff --git a/polymorphism/StaticPolymorphism.java b/polymorphism/StaticPolymorphism.java index 3a699528..bb6c0614 100644 --- a/polymorphism/StaticPolymorphism.java +++ b/polymorphism/StaticPolymorphism.java @@ -23,7 +23,7 @@ class StaticSub extends StaticSuper { public class StaticPolymorphism { public static void main(String[] args) { StaticSuper sup = new StaticSub(); // Upcast - System.out.println(sup.staticGet()); + System.out.println(StaticSuper.staticGet()); System.out.println(sup.dynamicGet()); } } /* Output: diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java index 38900388..2a84161b 100644 --- a/references/CopyConstructor.java +++ b/references/CopyConstructor.java @@ -123,8 +123,14 @@ public class CopyConstructor { Object obj = ct.newInstance(new Object[] { t }); System.out.println("In ripen2, t is a " + obj.getClass().getName()); + } catch(NoSuchMethodException | + SecurityException | + InstantiationException | + IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { + System.out.println(e); } - catch(Exception e) { System.out.println(e); } } public static void slice2(Fruit f) { try { @@ -133,8 +139,14 @@ public class CopyConstructor { Object obj = ct.newInstance(new Object[] { f }); System.out.println("In slice2, f is a " + obj.getClass().getName()); + } catch(NoSuchMethodException | + SecurityException | + InstantiationException | + IllegalAccessException | + IllegalArgumentException | + InvocationTargetException e) { + System.out.println(e); } - catch(Exception e) { System.out.println(e); } } public static void main(String[] args) { Tomato tomato = new Tomato(); diff --git a/remote/ptime/DisplayPerfectTime.java b/remote/ptime/DisplayPerfectTime.java index dbcca4a8..e916f7cf 100644 --- a/remote/ptime/DisplayPerfectTime.java +++ b/remote/ptime/DisplayPerfectTime.java @@ -2,6 +2,7 @@ // Uses remote object PerfectTime // {RunByHand} package remote.ptime; +import java.net.MalformedURLException; import java.rmi.*; import java.rmi.registry.*; @@ -15,7 +16,9 @@ public class DisplayPerfectTime { for(int i = 0; i < 10; i++) System.out.println("Perfect time = " + t.getPerfectTime()); - } catch(Exception e) { + } catch(NotBoundException | + MalformedURLException | + RemoteException e) { e.printStackTrace(); } } diff --git a/remote/ptime/PerfectTime.java b/remote/ptime/PerfectTime.java index 09630725..5f20a6a6 100644 --- a/remote/ptime/PerfectTime.java +++ b/remote/ptime/PerfectTime.java @@ -30,7 +30,9 @@ public class PerfectTime Naming.bind( "//MindviewToshibaLaptop:2005/PerfectTime", pt); System.out.println("Ready to do time"); - } catch(Exception e) { + } catch(RemoteException | + AlreadyBoundException | + MalformedURLException e) { e.printStackTrace(); } } diff --git a/typeinfo/FilledList.java b/typeinfo/FilledList.java index 5d0b4be8..a3c6a115 100644 --- a/typeinfo/FilledList.java +++ b/typeinfo/FilledList.java @@ -16,7 +16,8 @@ public class FilledList { try { for(int i = 0; i < nElements; i++) result.add(type.newInstance()); - } catch(Exception e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } return result; diff --git a/typeinfo/pets/PetCreator.java b/typeinfo/pets/PetCreator.java index 868b65f7..f12b80ca 100644 --- a/typeinfo/pets/PetCreator.java +++ b/typeinfo/pets/PetCreator.java @@ -11,9 +11,8 @@ public abstract class PetCreator { int n = rand.nextInt(types().size()); try { return types().get(n).newInstance(); - } catch(InstantiationException e) { - throw new RuntimeException(e); - } catch(IllegalAccessException e) { + } catch(InstantiationException | + IllegalAccessException e) { throw new RuntimeException(e); } }