package class6_1_MultithreadPrimeAppJava_start; import javax.swing.*; import java.awt.*; /** * This GUI class displays the most recently found prime number. */ public class PrimeApp extends JFrame { private PrimeFinder primeFinder = new PrimeFinder(this); private final JLabel recentPrimeLabel; public static void main(String[] ignored) { new PrimeApp(); } public PrimeApp() { setSize(400, 300); setLayout(new FlowLayout()); setDefaultCloseOperation(EXIT_ON_CLOSE); //--- The main window --- recentPrimeLabel = new JLabel(); recentPrimeLabel.setText("Latest prime: (none)"); add(recentPrimeLabel); JButton button = new JButton("Find Primes"); button.addActionListener(l->startPrimes()); add(button); //--- The menu bar --- JMenuBar bar = new JMenuBar(); JMenu menu = new JMenu("Actions"); JMenuItem item = new JMenuItem("Start finding primes"); item.addActionListener(l->startPrimes()); menu.add(item); item = new JMenuItem("Stop finding primes"); item.addActionListener(l->stopPrimes()); menu.add(item); bar.add(menu); setJMenuBar(bar); setVisible(true); } public void startPrimes() { primeFinder.findPrimes(); } public void stopPrimes() { // Spring 2017: Bug fixed after class 6-1: // This was stopping a different thread // instead of asking primeFinder to stop the thread. // This version of the code // has been corrected so that stop works. if(primeFinder == null) { System.err.println("Cannot interrupt worker: primeFinder variable is null"); } else { System.out.println("Interrupting worker."); primeFinder.interrupt(); } } /** * Sets the most recently found prime text. Client must provide the "Latest prime:" prefix as well. * @param text The complete new text for the label. */ public void setRecentPrime(String text) { SwingUtilities.invokeLater(() -> recentPrimeLabel.setText(text)); } }