package class6_1_MultithreadPrimeApp; import javax.swing.*; import java.awt.*; public class PrimeApp extends JFrame { private PrimeFinder primeFinder = new PrimeFinder(this); private final JLabel recentPrimeLabel; private Thread worker; 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() { System.out.println("Interrupting worker."); worker.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)); } }